01: /*
02: * Created on Apr 1, 2005
03: */
04: package uk.org.ponder.dateutil;
05:
06: import java.text.SimpleDateFormat;
07: import java.util.Date;
08: import java.util.TimeZone;
09:
10: /**
11: * A thread-local SimpleDateFormat wrapper. If the default constructor is
12: * used, supplies a W3C standard date format with millisecond resolution.
13: * This class is somewhat useful since construction of a SimpleDateFormat runs
14: * at around 13µs (2Ghz A64), with ThreadLocal gets around 300 times faster at
15: * 40ns or so. NB, GregorianCalendar runs at about 2µs.
16: * @author Antranig Basman (antranig@caret.cam.ac.uk)
17: *
18: */
19: public class LocalSDF {
20: /** this represents W3C (ISO-8601) standard dates as defined in
21: * http://www.w3.org/TR/NOTE-datetime */
22: public static final String W3C_DATE = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
23: /** An 8601 format with a variable timezone **/
24: public static final String W3C_DATE_TZ = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
25: /** An 8601 format with a truncated (forced) timezone **/
26: public static final String W3C_DATE_NOTZ = "yyyy-MM-dd'T'HH:mm:ss.SSS";
27: /** A format to easy breaking dates into field representations **/
28: public static final String BREAKER_DATE = "ddMMyyyyHHmmss";
29:
30: public static LocalSDF w3cformat = new LocalSDF();
31: public static LocalSDF breakformat = new LocalSDF(BREAKER_DATE);
32:
33: private String formatstring;
34: private ThreadLocal formatter = new ThreadLocal() {
35: public Object initialValue() {
36: if (formatstring == null) {
37: SimpleDateFormat format = new SimpleDateFormat(W3C_DATE);
38: format.setTimeZone(TimeZone.getTimeZone("UTC"));
39: format.setLenient(false);
40: return format;
41: }
42: return new SimpleDateFormat(formatstring);
43: }
44: };
45:
46: public LocalSDF() {
47: }
48:
49: public LocalSDF(String formatstring) {
50: this .formatstring = formatstring;
51: }
52:
53: public SimpleDateFormat get() {
54: return (SimpleDateFormat) formatter.get();
55: }
56:
57: public String format(Date toformat) {
58: return get().format(toformat);
59: }
60:
61: public Date parse(String datestring) {
62: Date parsed = DateUtil.parse(get(), datestring);
63: return parsed;
64: }
65: }
|