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

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

fix #16995 - fix timestamp in GPX exports (patch by cmuelle8) + use Java 8 unsigned int API

  • Property svn:eol-style set to native
File size: 13.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.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 String fromTimestamp(long timestamp) {
156        return fromTimestampInMillis(TimeUnit.SECONDS.toMillis(timestamp));
157    }
158
159    /**
160     * Formats a date to the XML UTC format regardless of current locale.
161     * @param timestamp number of milliseconds since the epoch
162     * @return The formatted date
163     * @since 14434
164     */
165    public static synchronized String fromTimestampInMillis(long timestamp) {
166        final ZonedDateTime temporal = Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.UTC);
167        return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(temporal);
168    }
169
170    /**
171     * Formats a date to the XML UTC format regardless of current locale.
172     * @param timestamp number of seconds since the epoch
173     * @return The formatted date
174     */
175    public static synchronized String fromTimestamp(int timestamp) {
176        return fromTimestamp(Integer.toUnsignedLong(timestamp));
177    }
178
179    /**
180     * Formats a date to the XML UTC format regardless of current locale.
181     * @param date The date to format
182     * @return The formatted date
183     */
184    public static synchronized String fromDate(Date date) {
185        final ZonedDateTime temporal = date.toInstant().atZone(ZoneOffset.UTC);
186        return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(temporal);
187    }
188
189    /**
190     * Null-safe date cloning method.
191     * @param d date to clone, or null
192     * @return cloned date, or null
193     * @since 11878
194     */
195    public static Date cloneDate(Date d) {
196        return d != null ? (Date) d.clone() : null;
197    }
198
199    private static boolean checkLayout(String text, String pattern) {
200        if (text.length() != pattern.length())
201            return false;
202        for (int i = 0; i < pattern.length(); i++) {
203            char pc = pattern.charAt(i);
204            char tc = text.charAt(i);
205            if (pc == 'x' && Character.isDigit(tc))
206                continue;
207            else if (pc == 'x' || pc != tc)
208                return false;
209        }
210        return true;
211    }
212
213    private static int num(char c) {
214        return c - '0';
215    }
216
217    private static int parsePart2(String str, int off) {
218        return 10 * num(str.charAt(off)) + num(str.charAt(off + 1));
219    }
220
221    private static int parsePart3(String str, int off) {
222        return 100 * num(str.charAt(off)) + 10 * num(str.charAt(off + 1)) + num(str.charAt(off + 2));
223    }
224
225    private static int parsePart4(String str, int off) {
226        return 1000 * num(str.charAt(off)) + 100 * num(str.charAt(off + 1)) + 10 * num(str.charAt(off + 2)) + num(str.charAt(off + 3));
227    }
228
229    /**
230     * Returns a new {@code SimpleDateFormat} for date only, according to <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a>.
231     * @return a new ISO 8601 date format, for date only.
232     * @since 7299
233     */
234    public static SimpleDateFormat newIsoDateFormat() {
235        return new SimpleDateFormat("yyyy-MM-dd");
236    }
237
238    /**
239     * Returns a new {@code SimpleDateFormat} for date and time, according to <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a>.
240     * @return a new ISO 8601 date format, for date and time.
241     * @since 7299
242     */
243    public static SimpleDateFormat newIsoDateTimeFormat() {
244        return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
245    }
246
247    /**
248     * Returns a new {@code SimpleDateFormat} for date and time, according to format used in OSM API errors.
249     * @return a new date format, for date and time, to use for OSM API error handling.
250     * @since 7299
251     */
252    public static SimpleDateFormat newOsmApiDateTimeFormat() {
253        // Example: "2010-09-07 14:39:41 UTC".
254        // Always parsed with US locale regardless of the current locale in JOSM
255        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.US);
256    }
257
258    /**
259     * Returns the date format to be used for current user, based on user preferences.
260     * @param dateStyle The date style as described in {@link DateFormat#getDateInstance}. Ignored if "ISO dates" option is set
261     * @return The date format
262     * @since 7299
263     */
264    public static DateFormat getDateFormat(int dateStyle) {
265        if (PROP_ISO_DATES.get()) {
266            return newIsoDateFormat();
267        } else {
268            return DateFormat.getDateInstance(dateStyle, Locale.getDefault());
269        }
270    }
271
272    /**
273     * Returns the date format used for GPX waypoints.
274     * @return the date format used for GPX waypoints
275     * @since 14055
276     */
277    public static DateFormat getGpxFormat() {
278        SimpleDateFormat result = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
279        result.setTimeZone(UTC);
280        return result;
281    }
282
283    /**
284     * Formats a date to be displayed to current user, based on user preferences.
285     * @param date The date to display. Must not be {@code null}
286     * @param dateStyle The date style as described in {@link DateFormat#getDateInstance}. Ignored if "ISO dates" option is set
287     * @return The formatted date
288     * @since 7299
289     */
290    public static String formatDate(Date date, int dateStyle) {
291        CheckParameterUtil.ensureParameterNotNull(date, "date");
292        return getDateFormat(dateStyle).format(date);
293    }
294
295    /**
296     * Returns the time format to be used for current user, based on user preferences.
297     * @param timeStyle The time style as described in {@link DateFormat#getTimeInstance}. Ignored if "ISO dates" option is set
298     * @return The time format
299     * @since 7299
300     */
301    public static DateFormat getTimeFormat(int timeStyle) {
302        if (PROP_ISO_DATES.get()) {
303            // This is not strictly conform to ISO 8601. We just want to avoid US-style times such as 3.30pm
304            return new SimpleDateFormat("HH:mm:ss");
305        } else {
306            return DateFormat.getTimeInstance(timeStyle, Locale.getDefault());
307        }
308    }
309
310    /**
311     * Formats a time to be displayed to current user, based on user preferences.
312     * @param time The time to display. Must not be {@code null}
313     * @param timeStyle The time style as described in {@link DateFormat#getTimeInstance}. Ignored if "ISO dates" option is set
314     * @return The formatted time
315     * @since 7299
316     */
317    public static String formatTime(Date time, int timeStyle) {
318        CheckParameterUtil.ensureParameterNotNull(time, "time");
319        return getTimeFormat(timeStyle).format(time);
320    }
321
322    /**
323     * Returns the date/time format to be used for current user, based on user preferences.
324     * @param dateStyle The date style as described in {@link DateFormat#getDateTimeInstance}. Ignored if "ISO dates" option is set
325     * @param timeStyle The time style as described in {@code DateFormat.getDateTimeInstance}. Ignored if "ISO dates" option is set
326     * @return The date/time format
327     * @since 7299
328     */
329    public static DateFormat getDateTimeFormat(int dateStyle, int timeStyle) {
330        if (PROP_ISO_DATES.get()) {
331            // This is not strictly conform to ISO 8601. We just want to avoid US-style times such as 3.30pm
332            // and we don't want to use the 'T' separator as a space character is much more readable
333            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
334        } else {
335            return DateFormat.getDateTimeInstance(dateStyle, timeStyle, Locale.getDefault());
336        }
337    }
338
339    /**
340     * Formats a date/time to be displayed to current user, based on user preferences.
341     * @param datetime The date/time to display. Must not be {@code null}
342     * @param dateStyle The date style as described in {@link DateFormat#getDateTimeInstance}. Ignored if "ISO dates" option is set
343     * @param timeStyle The time style as described in {@code DateFormat.getDateTimeInstance}. Ignored if "ISO dates" option is set
344     * @return The formatted date/time
345     * @since 7299
346     */
347    public static String formatDateTime(Date datetime, int dateStyle, int timeStyle) {
348        CheckParameterUtil.ensureParameterNotNull(datetime, "datetime");
349        return getDateTimeFormat(dateStyle, timeStyle).format(datetime);
350    }
351}
Note: See TracBrowser for help on using the repository browser.