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

Last change on this file since 11288 was 11288, checked in by simon04, 7 years ago

see #13376 - Use TimeUnit instead of combinations of 1000/60/60/24

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