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

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

fix #14103 - GPX → OSM: convert additional tags

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