From: Alex Twisleton-Wykeham-F. <al...@fi...> - 2006-03-27 18:01:41
|
On Mon 27 March 2006 17:36, Keats Kirsch wrote: > >I'll also look at making $Text.formatDate cache the SimpleTextFormat > > objects that it creates and run some profiling to see whether or not this > > is really an advantage... > > Yes the formatDate() method was kind of a quick hack. At one point I > had written a DateTool, but I never got it clean enough to commit to CVS > (and now I've lost it). Perhaps I'll give it another whack. It's > actually fairly complicated, given all the different date formats and > localization etc. It would be nice if the tool could pick up the locale > from the request, but then it would be Servlet specific. But something > simple would probably be useful for parsing and formatting dates. In the meantime, adding something like this to TextTool will help:- private final static Map __simpleDateFormats = new HashMap(); public static String formatDate (Date date, String format) { SimpleDateFormat formatter = null; synchronized (__simpleDateFormats) { formatter = (SimpleDateFormat) __simpleDateFormats.get(format); if (formatter == null) { formatter = new SimpleDateFormat(format); __formatters.put(format, formatter); } } return formatter.format(date); } I'll run some tests and see if it is worth the added complexity from a performance viewpoint. > I'm thinking a factory that would produce date wrappers. E.g., > > #set $dt = $DateFactory.parse("27-Mar-2006", "dd-MMM-yyyy") > #set $dt.Format.Short = "MM/dd/yyyy" > #set $dt.Format.Default = "dd-MMM-yyyy" > > Default format: $dt ==> 27-Mar-2006 > Short format: $dt.Format.Short ==> 02/27/2006 > > #set $dt = $dt.addMonths(1) > New date: $dt ==> 27-Apr-2006 Why not make it so that the wrapper class extends Date so that you can then also used the wrapped class as a drop-in replacement for Date in other methods. Also, why not make the wrapper include a hashtable accessor that enables you to extend the number of registered formats on it? e.g. $DateFactory.registerFormat("Short", "MM-dd-yyyy") #set $dateWrapper = $DateFactory.parse("27-Mar-2006", "Short") $dateWrapper.Time --> java.util.Date.getTime() $dateWrapper.Short --> DateWrapper.get("Short") --> String (by querying DateFactory for the SimpleDateFormatter registered as "Short" and then formatting itself using this format) If I was really looking for flexibility you could also make cascading parsers which would let you do things like this:- $DateFactory.registerFormat("Long", "hh:MM:ss MM-dd-yyyy") $DateFactory.registerFormat("Medium", "hh:MM MM-dd-yyyy") $DateFactory.registerFormat("Short", "MM-dd-yyyy") #set $dateWrapper = $DateFactory.parse("22-05-1971") and it would iterate through the registered formatters in order finding one that can parse the supplied text... <snip> Alex |