source: josm/trunk/src/org/openstreetmap/josm/tools/date/DateUtils.java@ 10475

Last change on this file since 10475 was 10475, checked in by Don-vip, 8 years ago

fix #13045 - Inconsistent timezone handling in tests/nmea (patch by michael2402) - gsoc-core

  • Property svn:eol-style set to native
File size: 12.9 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools.date;
3
4import java.text.DateFormat;
5import java.text.ParsePosition;
6import java.text.SimpleDateFormat;
7import java.util.Calendar;
8import java.util.Date;
9import java.util.GregorianCalendar;
10import java.util.Locale;
11import java.util.TimeZone;
12
13import javax.xml.datatype.DatatypeConfigurationException;
14import javax.xml.datatype.DatatypeFactory;
15import javax.xml.datatype.XMLGregorianCalendar;
16
17import org.openstreetmap.josm.Main;
18import org.openstreetmap.josm.data.preferences.BooleanProperty;
19import org.openstreetmap.josm.tools.CheckParameterUtil;
20import org.openstreetmap.josm.tools.UncheckedParseException;
21
22/**
23 * A static utility class dealing with:
24 * <ul>
25 * <li>parsing XML date quickly and formatting a date to the XML UTC format regardless of current locale</li>
26 * <li>providing a single entry point for formatting dates to be displayed in JOSM GUI, based on user preferences</li>
27 * </ul>
28 * @author nenik
29 */
30public final class DateUtils {
31
32 /**
33 * The UTC time zone.
34 */
35 public static final TimeZone UTC = TimeZone.getTimeZone("UTC");
36
37 protected DateUtils() {
38 // Hide default constructor for utils classes
39 }
40
41 /**
42 * Property to enable display of ISO dates globally.
43 * @since 7299
44 */
45 public static final BooleanProperty PROP_ISO_DATES = new BooleanProperty("iso.dates", false);
46
47 /**
48 * A shared instance used for conversion between individual date fields
49 * and long millis time. It is guarded against conflict by the class lock.
50 * The shared instance is used because the construction, together
51 * with the timezone lookup, is very expensive.
52 */
53 private static final GregorianCalendar calendar = new GregorianCalendar(UTC);
54 private static final GregorianCalendar calendarLocale = new GregorianCalendar(TimeZone.getDefault());
55 private static final DatatypeFactory XML_DATE;
56
57 static {
58 calendar.setTimeInMillis(0);
59 calendarLocale.setTimeInMillis(0);
60
61 DatatypeFactory fact = null;
62 try {
63 fact = DatatypeFactory.newInstance();
64 } catch (DatatypeConfigurationException ce) {
65 Main.error(ce);
66 }
67 XML_DATE = fact;
68 }
69
70 /**
71 * Parses XML date quickly, regardless of current locale.
72 * @param str The XML date as string
73 * @return The date
74 * @throws UncheckedParseException if the date does not match any of the supported date formats
75 */
76 public static synchronized Date fromString(String str) throws UncheckedParseException {
77 return new Date(tsFromString(str));
78 }
79
80 /**
81 * Parses XML date quickly, regardless of current locale.
82 * @param str The XML date as string
83 * @return The date in milliseconds since epoch
84 * @throws UncheckedParseException if the date does not match any of the supported date formats
85 */
86 public static synchronized long tsFromString(String str) throws UncheckedParseException {
87 // "2007-07-25T09:26:24{Z|{+|-}01[:00]}"
88 if (checkLayout(str, "xxxx-xx-xxTxx:xx:xxZ") ||
89 checkLayout(str, "xxxx-xx-xxTxx:xx:xx") ||
90 checkLayout(str, "xxxx:xx:xx xx:xx:xx") ||
91 checkLayout(str, "xxxx-xx-xx xx:xx:xx UTC") ||
92 checkLayout(str, "xxxx-xx-xxTxx:xx:xx+xx") ||
93 checkLayout(str, "xxxx-xx-xxTxx:xx:xx-xx") ||
94 checkLayout(str, "xxxx-xx-xxTxx:xx:xx+xx:00") ||
95 checkLayout(str, "xxxx-xx-xxTxx:xx:xx-xx:00")) {
96 final Calendar c = checkLayout(str, "xxxx:xx:xx xx:xx:xx") ? calendarLocale : calendar; // consider EXIF date in default timezone
97 c.set(
98 parsePart4(str, 0),
99 parsePart2(str, 5)-1,
100 parsePart2(str, 8),
101 parsePart2(str, 11),
102 parsePart2(str, 14),
103 parsePart2(str, 17));
104 c.set(Calendar.MILLISECOND, 0);
105
106 if (str.length() == 22 || str.length() == 25) {
107 int plusHr = parsePart2(str, 20);
108 int mul = str.charAt(19) == '+' ? -3600000 : 3600000;
109 return c.getTimeInMillis()+plusHr*mul;
110 }
111
112 return c.getTimeInMillis();
113 } else if (checkLayout(str, "xxxx-xx-xxTxx:xx:xx.xxxZ") ||
114 checkLayout(str, "xxxx-xx-xxTxx:xx:xx.xxx") ||
115 checkLayout(str, "xxxx:xx:xx xx:xx:xx.xxx") ||
116 checkLayout(str, "xxxx-xx-xxTxx:xx:xx.xxx+xx:00") ||
117 checkLayout(str, "xxxx-xx-xxTxx:xx:xx.xxx-xx:00")) {
118 final Calendar c = checkLayout(str, "xxxx:xx:xx xx:xx:xx.xxx") ? calendarLocale : calendar; // consider EXIF date in default timezone
119 c.set(
120 parsePart4(str, 0),
121 parsePart2(str, 5)-1,
122 parsePart2(str, 8),
123 parsePart2(str, 11),
124 parsePart2(str, 14),
125 parsePart2(str, 17));
126 c.set(Calendar.MILLISECOND, 0);
127 long millis = parsePart3(str, 20);
128 if (str.length() == 29) {
129 millis += parsePart2(str, 24) * (str.charAt(23) == '+' ? -3600000 : 3600000);
130 }
131
132 return c.getTimeInMillis() + millis;
133 } else {
134 // example date format "18-AUG-08 13:33:03"
135 SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yy HH:mm:ss");
136 Date d = f.parse(str, new ParsePosition(0));
137 if (d != null)
138 return d.getTime();
139 }
140
141 try {
142 return XML_DATE.newXMLGregorianCalendar(str).toGregorianCalendar().getTimeInMillis();
143 } catch (IllegalArgumentException ex) {
144 throw new UncheckedParseException("The date string (" + str + ") could not be parsed.", ex);
145 }
146 }
147
148 private static String toXmlFormat(GregorianCalendar cal) {
149 XMLGregorianCalendar xgc = XML_DATE.newXMLGregorianCalendar(cal);
150 if (cal.get(Calendar.MILLISECOND) == 0) {
151 xgc.setFractionalSecond(null);
152 }
153 return xgc.toXMLFormat();
154 }
155
156 /**
157 * Formats a date to the XML UTC format regardless of current locale.
158 * @param timestamp number of seconds since the epoch
159 * @return The formatted date
160 */
161 public static synchronized String fromTimestamp(int timestamp) {
162 calendar.setTimeInMillis(timestamp * 1000L);
163 return toXmlFormat(calendar);
164 }
165
166 /**
167 * Formats a date to the XML UTC format regardless of current locale.
168 * @param date The date to format
169 * @return The formatted date
170 */
171 public static synchronized String fromDate(Date date) {
172 calendar.setTime(date);
173 return toXmlFormat(calendar);
174 }
175
176 private static boolean checkLayout(String text, String pattern) {
177 if (text.length() != pattern.length())
178 return false;
179 for (int i = 0; i < pattern.length(); i++) {
180 char pc = pattern.charAt(i);
181 char tc = text.charAt(i);
182 if (pc == 'x' && Character.isDigit(tc))
183 continue;
184 else if (pc == 'x' || pc != tc)
185 return false;
186 }
187 return true;
188 }
189
190 private static int num(char c) {
191 return c - '0';
192 }
193
194 private static int parsePart2(String str, int off) {
195 return 10 * num(str.charAt(off)) + num(str.charAt(off + 1));
196 }
197
198 private static int parsePart3(String str, int off) {
199 return 100 * num(str.charAt(off)) + 10 * num(str.charAt(off + 1)) + num(str.charAt(off + 2));
200 }
201
202 private static int parsePart4(String str, int off) {
203 return 1000 * num(str.charAt(off)) + 100 * num(str.charAt(off + 1)) + 10 * num(str.charAt(off + 2)) + num(str.charAt(off + 3));
204 }
205
206 /**
207 * Returns a new {@code SimpleDateFormat} for date only, according to <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a>.
208 * @return a new ISO 8601 date format, for date only.
209 * @since 7299
210 */
211 public static SimpleDateFormat newIsoDateFormat() {
212 return new SimpleDateFormat("yyyy-MM-dd");
213 }
214
215 /**
216 * Returns a new {@code SimpleDateFormat} for date and time, according to <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a>.
217 * @return a new ISO 8601 date format, for date and time.
218 * @since 7299
219 */
220 public static SimpleDateFormat newIsoDateTimeFormat() {
221 return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
222 }
223
224 /**
225 * Returns a new {@code SimpleDateFormat} for date and time, according to format used in OSM API errors.
226 * @return a new date format, for date and time, to use for OSM API error handling.
227 * @since 7299
228 */
229 public static SimpleDateFormat newOsmApiDateTimeFormat() {
230 // Example: "2010-09-07 14:39:41 UTC".
231 // Always parsed with US locale regardless of the current locale in JOSM
232 return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.US);
233 }
234
235 /**
236 * Returns the date format to be used for current user, based on user preferences.
237 * @param dateStyle The date style as described in {@link DateFormat#getDateInstance}. Ignored if "ISO dates" option is set
238 * @return The date format
239 * @since 7299
240 */
241 public static DateFormat getDateFormat(int dateStyle) {
242 if (PROP_ISO_DATES.get()) {
243 return newIsoDateFormat();
244 } else {
245 return DateFormat.getDateInstance(dateStyle, Locale.getDefault());
246 }
247 }
248
249 /**
250 * Formats a date to be displayed to current user, based on user preferences.
251 * @param date The date to display. Must not be {@code null}
252 * @param dateStyle The date style as described in {@link DateFormat#getDateInstance}. Ignored if "ISO dates" option is set
253 * @return The formatted date
254 * @since 7299
255 */
256 public static String formatDate(Date date, int dateStyle) {
257 CheckParameterUtil.ensureParameterNotNull(date, "date");
258 return getDateFormat(dateStyle).format(date);
259 }
260
261 /**
262 * Returns the time format to be used for current user, based on user preferences.
263 * @param timeStyle The time style as described in {@link DateFormat#getTimeInstance}. Ignored if "ISO dates" option is set
264 * @return The time format
265 * @since 7299
266 */
267 public static DateFormat getTimeFormat(int timeStyle) {
268 if (PROP_ISO_DATES.get()) {
269 // This is not strictly conform to ISO 8601. We just want to avoid US-style times such as 3.30pm
270 return new SimpleDateFormat("HH:mm:ss");
271 } else {
272 return DateFormat.getTimeInstance(timeStyle, Locale.getDefault());
273 }
274 }
275
276 /**
277 * Formats a time to be displayed to current user, based on user preferences.
278 * @param time The time to display. Must not be {@code null}
279 * @param timeStyle The time style as described in {@link DateFormat#getTimeInstance}. Ignored if "ISO dates" option is set
280 * @return The formatted time
281 * @since 7299
282 */
283 public static String formatTime(Date time, int timeStyle) {
284 CheckParameterUtil.ensureParameterNotNull(time, "time");
285 return getTimeFormat(timeStyle).format(time);
286 }
287
288 /**
289 * Returns the date/time format to be used for current user, based on user preferences.
290 * @param dateStyle The date style as described in {@link DateFormat#getDateTimeInstance}. Ignored if "ISO dates" option is set
291 * @param timeStyle The time style as described in {@code DateFormat.getDateTimeInstance}. Ignored if "ISO dates" option is set
292 * @return The date/time format
293 * @since 7299
294 */
295 public static DateFormat getDateTimeFormat(int dateStyle, int timeStyle) {
296 if (PROP_ISO_DATES.get()) {
297 // This is not strictly conform to ISO 8601. We just want to avoid US-style times such as 3.30pm
298 // and we don't want to use the 'T' separator as a space character is much more readable
299 return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
300 } else {
301 return DateFormat.getDateTimeInstance(dateStyle, timeStyle, Locale.getDefault());
302 }
303 }
304
305 /**
306 * Formats a date/time to be displayed to current user, based on user preferences.
307 * @param datetime The date/time to display. Must not be {@code null}
308 * @param dateStyle The date style as described in {@link DateFormat#getDateTimeInstance}. Ignored if "ISO dates" option is set
309 * @param timeStyle The time style as described in {@code DateFormat.getDateTimeInstance}. Ignored if "ISO dates" option is set
310 * @return The formatted date/time
311 * @since 7299
312 */
313 public static String formatDateTime(Date datetime, int dateStyle, int timeStyle) {
314 CheckParameterUtil.ensureParameterNotNull(datetime, "datetime");
315 return getDateTimeFormat(dateStyle, timeStyle).format(datetime);
316 }
317
318 /**
319 * Allows to override the timezone for unit tests.
320 * @param zone the timezone to use
321 */
322 protected static synchronized void setTimeZone(TimeZone zone) {
323 calendarLocale.setTimeZone(zone);
324 }
325}
Note: See TracBrowser for help on using the repository browser.