1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package net.fortuna.ical4j.util;
35
36 import java.text.ParseException;
37 import java.text.SimpleDateFormat;
38 import java.util.Date;
39 import java.util.TimeZone;
40
41 import org.apache.commons.logging.Log;
42 import org.apache.commons.logging.LogFactory;
43
44 /***
45 * Defines a format for all iCalendar date-times.
46 * @author benfortuna
47 */
48 public final class DateTimeFormat {
49
50 private static final String DEFAULT_PATTERN = "yyyyMMdd'T'HHmmss";
51
52 private static final String UTC_PATTERN = "yyyyMMdd'T'HHmmss'Z'";
53
54 private static Log log = LogFactory.getLog(DateTimeFormat.class);
55
56 private static DateTimeFormat instance = new DateTimeFormat();
57
58 private java.text.DateFormat defaultFormat;
59
60 private java.text.DateFormat utcFormat;
61
62 /***
63 * Constructor made private to enforce singleton.
64 */
65 private DateTimeFormat() {
66 defaultFormat = new SimpleDateFormat(DEFAULT_PATTERN);
67
68 utcFormat = new SimpleDateFormat(UTC_PATTERN);
69 utcFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
70 }
71
72 /***
73 * @return Returns the instance.
74 */
75 public static DateTimeFormat getInstance() {
76 return instance;
77 }
78
79 /***
80 * Returns a string representation of the specified
81 * date in UTC format.
82 * @param date a date to format
83 * @return a string representation of the specified date
84 */
85 public String format(final Date date) {
86 return format(date, true);
87 }
88
89 /***
90 * Returns a string representation of the specified
91 * date.
92 * @param date a date to format
93 * @param utc indicates whether to format as UTC time
94 * @return a string representation of the specified date
95 */
96 public String format(final Date date, final boolean utc) {
97 if (utc) {
98 return utcFormat.format(date);
99 }
100
101 return defaultFormat.format(date);
102 }
103
104 /***
105 * @param string a string representation of a date-time
106 * @return a date parsed from the specified string representation
107 * @throws java.text.ParseException thrown if the specified string
108 * is not a valid representation of a date-time
109 */
110 public Date parse(final String string) throws ParseException {
111 try {
112 return utcFormat.parse(string);
113 }
114 catch (ParseException pe) {
115 return defaultFormat.parse(string);
116 }
117 }
118 }