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

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

fix #16633 - add robustness against invalid time entries in GPX files

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