001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools.date;
003
004import java.text.DateFormat;
005import java.text.ParsePosition;
006import java.text.SimpleDateFormat;
007import java.time.DateTimeException;
008import java.time.Instant;
009import java.time.ZoneId;
010import java.time.ZoneOffset;
011import java.time.ZonedDateTime;
012import java.time.format.DateTimeFormatter;
013import java.time.format.DateTimeFormatterBuilder;
014import java.time.format.FormatStyle;
015import java.util.Date;
016import java.util.Locale;
017import java.util.TimeZone;
018import java.util.concurrent.TimeUnit;
019
020import org.openstreetmap.josm.data.preferences.BooleanProperty;
021import org.openstreetmap.josm.tools.CheckParameterUtil;
022import org.openstreetmap.josm.tools.UncheckedParseException;
023
024/**
025 * A static utility class dealing with:
026 * <ul>
027 * <li>parsing XML date quickly and formatting a date to the XML UTC format regardless of current locale</li>
028 * <li>providing a single entry point for formatting dates to be displayed in JOSM GUI, based on user preferences</li>
029 * </ul>
030 * @author nenik
031 */
032public final class DateUtils {
033
034    /**
035     * The UTC time zone.
036     */
037    public static final TimeZone UTC = TimeZone.getTimeZone(ZoneOffset.UTC);
038
039    /**
040     * Property to enable display of ISO dates globally.
041     * @since 7299
042     */
043    public static final BooleanProperty PROP_ISO_DATES = new BooleanProperty("iso.dates", false);
044
045    /**
046     * Constructs a new {@code DateUtils}.
047     */
048    private DateUtils() {
049        // Hide default constructor for utils classes
050    }
051
052    /**
053     * Parses XML date quickly, regardless of current locale.
054     * @param str The XML date as string
055     * @return The date
056     * @throws UncheckedParseException if the date does not match any of the supported date formats
057     * @throws DateTimeException if the value of any field is out of range, or if the day-of-month is invalid for the month-year
058     */
059    public static Date fromString(String str) {
060        return new Date(tsFromString(str));
061    }
062
063    /**
064     * Parses XML date quickly, regardless of current locale.
065     * @param str The XML date as string
066     * @return The date in milliseconds since epoch
067     * @throws UncheckedParseException if the date does not match any of the supported date formats
068     * @throws DateTimeException if the value of any field is out of range, or if the day-of-month is invalid for the month-year
069     */
070    public static long tsFromString(String str) {
071        return parseInstant(str).toEpochMilli();
072    }
073
074    /**
075     * Parses the given date string quickly, regardless of current locale.
076     * @param str the date string
077     * @return the parsed instant
078     * @throws UncheckedParseException if the date does not match any of the supported date formats
079     */
080    public static Instant parseInstant(String str) {
081        // "2007-07-25T09:26:24{Z|{+|-}01[:00]}"
082        try {
083            if (checkLayout(str, "xxxx-xx-xx") ||
084                    checkLayout(str, "xxxx-xx") ||
085                    checkLayout(str, "xxxx")) {
086                final ZonedDateTime local = ZonedDateTime.of(
087                        parsePart4(str, 0),
088                        str.length() > 5 ? parsePart2(str, 5) : 1,
089                        str.length() > 8 ? parsePart2(str, 8) : 1,
090                        0, 0, 0, 0, ZoneOffset.UTC);
091                return local.toInstant();
092            } else if (checkLayout(str, "xxxx-xx-xxTxx:xx:xxZ") ||
093                    checkLayout(str, "xxxx-xx-xxTxx:xx:xx") ||
094                    checkLayout(str, "xxxx:xx:xx xx:xx:xx") ||
095                    checkLayout(str, "xxxx/xx/xx xx:xx:xx") ||
096                    checkLayout(str, "xxxx-xx-xx xx:xx:xxZ") ||
097                    checkLayout(str, "xxxx-xx-xx xx:xx:xx UTC") ||
098                    checkLayout(str, "xxxx-xx-xxTxx:xx:xx+xx") ||
099                    checkLayout(str, "xxxx-xx-xxTxx:xx:xx-xx") ||
100                    checkLayout(str, "xxxx-xx-xxTxx:xx:xx+xx:00") ||
101                    checkLayout(str, "xxxx-xx-xxTxx:xx:xx-xx:00")) {
102                final ZonedDateTime local = ZonedDateTime.of(
103                        parsePart4(str, 0),
104                        parsePart2(str, 5),
105                        parsePart2(str, 8),
106                        parsePart2(str, 11),
107                        parsePart2(str, 14),
108                        parsePart2(str, 17),
109                        0,
110                        ZoneOffset.UTC
111                );
112                if (str.length() == 22 || str.length() == 25) {
113                    final int plusHr = parsePart2(str, 20);
114                    return local.plusHours(str.charAt(19) == '+' ? -plusHr : plusHr).toInstant();
115                }
116                return local.toInstant();
117            } else if (checkLayout(str, "xxxx-xx-xxTxx:xx:xx.xxxZ") ||
118                    checkLayout(str, "xxxx-xx-xxTxx:xx:xx.xxx") ||
119                    checkLayout(str, "xxxx:xx:xx xx:xx:xx.xxx") ||
120                    checkLayout(str, "xxxx/xx/xx xx:xx:xx.xxx") ||
121                    checkLayout(str, "xxxx-xx-xxTxx:xx:xx.xxx+xx:00") ||
122                    checkLayout(str, "xxxx-xx-xxTxx:xx:xx.xxx-xx:00")) {
123                final ZonedDateTime local = ZonedDateTime.of(
124                        parsePart4(str, 0),
125                        parsePart2(str, 5),
126                        parsePart2(str, 8),
127                        parsePart2(str, 11),
128                        parsePart2(str, 14),
129                        parsePart2(str, 17),
130                        parsePart3(str, 20) * 1_000_000,
131                        ZoneOffset.UTC
132                );
133                if (str.length() == 29) {
134                    final int plusHr = parsePart2(str, 24);
135                    return local.plusHours(str.charAt(23) == '+' ? -plusHr : plusHr).toInstant();
136                }
137                return local.toInstant();
138            } else if (checkLayout(str, "xxxx/xx/xx xx:xx:xx.xxxxxx")) {
139                return ZonedDateTime.of(
140                        parsePart4(str, 0),
141                        parsePart2(str, 5),
142                        parsePart2(str, 8),
143                        parsePart2(str, 11),
144                        parsePart2(str, 14),
145                        parsePart2(str, 17),
146                        parsePart6(str, 20) * 1_000,
147                        ZoneOffset.UTC
148                ).toInstant();
149            } else {
150                // example date format "18-AUG-08 13:33:03"
151                SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yy HH:mm:ss");
152                Date d = f.parse(str, new ParsePosition(0));
153                if (d != null)
154                    return d.toInstant();
155            }
156
157            // slow path for fractional seconds different from millisecond precision
158            return ZonedDateTime.parse(str).toInstant();
159        } catch (IllegalArgumentException | DateTimeException ex) {
160            throw new UncheckedParseException("The date string (" + str + ") could not be parsed.", ex);
161        }
162    }
163
164    /**
165     * Formats a date to the XML UTC format regardless of current locale.
166     * @param timestamp number of seconds since the epoch
167     * @return The formatted date
168     * @since 14055
169     */
170    public static String fromTimestamp(long timestamp) {
171        return fromTimestampInMillis(TimeUnit.SECONDS.toMillis(timestamp));
172    }
173
174    /**
175     * Formats a date to the XML UTC format regardless of current locale.
176     * @param timestamp number of milliseconds since the epoch
177     * @return The formatted date
178     * @since 14434
179     */
180    public static String fromTimestampInMillis(long timestamp) {
181        final ZonedDateTime temporal = Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.UTC);
182        return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(temporal);
183    }
184
185    /**
186     * Formats a date to the XML UTC format regardless of current locale.
187     * @param timestamp number of seconds since the epoch
188     * @return The formatted date
189     */
190    public static String fromTimestamp(int timestamp) {
191        return fromTimestamp(Integer.toUnsignedLong(timestamp));
192    }
193
194    /**
195     * Formats a date to the XML UTC format regardless of current locale.
196     * @param date The date to format
197     * @return The formatted date
198     */
199    public static String fromDate(Date date) {
200        final ZonedDateTime temporal = date.toInstant().atZone(ZoneOffset.UTC);
201        return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(temporal);
202    }
203
204    /**
205     * Null-safe date cloning method.
206     * @param d date to clone, or null
207     * @return cloned date, or null
208     * @since 11878
209     */
210    public static Date cloneDate(Date d) {
211        return d != null ? (Date) d.clone() : null;
212    }
213
214    /**
215     * Check text for a specified layout
216     * @param text The text to check
217     * @param pattern The pattern to use
218     * @return {@code true} if the layout matches, otherwise {@code false}
219     */
220    private static boolean checkLayout(String text, String pattern) {
221        if (text.length() != pattern.length())
222            return false;
223        for (int i = 0; i < pattern.length(); i++) {
224            char pc = pattern.charAt(i);
225            char tc = text.charAt(i);
226            if (pc == 'x' && Character.isDigit(tc))
227                continue;
228            else if (pc == 'x' || pc != tc)
229                return false;
230        }
231        return true;
232    }
233
234    private static int num(char c) {
235        return c - '0';
236    }
237
238    private static int parsePart2(String str, int off) {
239        return 10 * num(str.charAt(off)) + num(str.charAt(off + 1));
240    }
241
242    private static int parsePart3(String str, int off) {
243        return 100 * num(str.charAt(off)) + 10 * num(str.charAt(off + 1)) + num(str.charAt(off + 2));
244    }
245
246    private static int parsePart4(String str, int off) {
247        return 1000 * num(str.charAt(off)) + 100 * num(str.charAt(off + 1)) + 10 * num(str.charAt(off + 2)) + num(str.charAt(off + 3));
248    }
249
250    private static int parsePart6(String str, int off) {
251        return 100_000 * num(str.charAt(off))
252              + 10_000 * num(str.charAt(off + 1))
253               + 1_000 * num(str.charAt(off + 2))
254                 + 100 * num(str.charAt(off + 3))
255                  + 10 * num(str.charAt(off + 4))
256                       + num(str.charAt(off + 5));
257    }
258
259    /**
260     * Returns a new {@code SimpleDateFormat} for date only, according to <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a>.
261     * @return a new ISO 8601 date format, for date only.
262     * @since 7299
263     */
264    public static SimpleDateFormat newIsoDateFormat() {
265        return new SimpleDateFormat("yyyy-MM-dd");
266    }
267
268    /**
269     * Returns the date format to be used for current user, based on user preferences.
270     * @param dateStyle The date style as described in {@link DateFormat#getDateInstance}. Ignored if "ISO dates" option is set
271     * @return The date format
272     * @since 7299
273     */
274    public static DateFormat getDateFormat(int dateStyle) {
275        if (Boolean.TRUE.equals(PROP_ISO_DATES.get())) {
276            return newIsoDateFormat();
277        } else {
278            return DateFormat.getDateInstance(dateStyle, Locale.getDefault());
279        }
280    }
281
282    /**
283     * Returns the date formatter to be used for current user, based on user preferences.
284     * @param dateStyle The date style. Ignored if "ISO dates" option is set.
285     * @return The date format
286     */
287    public static DateTimeFormatter getDateFormatter(FormatStyle dateStyle) {
288        DateTimeFormatter formatter = Boolean.TRUE.equals(PROP_ISO_DATES.get())
289                ? DateTimeFormatter.ISO_LOCAL_DATE
290                : DateTimeFormatter.ofLocalizedDate(dateStyle);
291        return formatter.withZone(ZoneId.systemDefault());
292    }
293
294    /**
295     * Formats a date to be displayed to current user, based on user preferences.
296     * @param date The date to display. Must not be {@code null}
297     * @param dateStyle The date style as described in {@link DateFormat#getDateInstance}. Ignored if "ISO dates" option is set
298     * @return The formatted date
299     * @since 7299
300     */
301    public static String formatDate(Date date, int dateStyle) {
302        CheckParameterUtil.ensureParameterNotNull(date, "date");
303        return getDateFormat(dateStyle).format(date);
304    }
305
306    /**
307     * Returns the time format to be used for current user, based on user preferences.
308     * @param timeStyle The time style as described in {@link DateFormat#getTimeInstance}. Ignored if "ISO dates" option is set
309     * @return The time format
310     * @since 7299
311     */
312    public static DateFormat getTimeFormat(int timeStyle) {
313        if (Boolean.TRUE.equals(PROP_ISO_DATES.get())) {
314            // This is not strictly conform to ISO 8601. We just want to avoid US-style times such as 3.30pm
315            return new SimpleDateFormat("HH:mm:ss");
316        } else {
317            return DateFormat.getTimeInstance(timeStyle, Locale.getDefault());
318        }
319    }
320
321    /**
322     * Returns the time formatter to be used for current user, based on user preferences.
323     * @param timeStyle The time style. Ignored if "ISO dates" option is set.
324     * @return The time format
325     */
326    public static DateTimeFormatter getTimeFormatter(FormatStyle timeStyle) {
327        DateTimeFormatter formatter = Boolean.TRUE.equals(PROP_ISO_DATES.get())
328                ? DateTimeFormatter.ISO_LOCAL_TIME
329                : DateTimeFormatter.ofLocalizedTime(timeStyle);
330        return formatter.withZone(ZoneId.systemDefault());
331    }
332
333    /**
334     * Formats a time to be displayed to current user, based on user preferences.
335     * @param time The time to display. Must not be {@code null}
336     * @param timeStyle The time style as described in {@link DateFormat#getTimeInstance}. Ignored if "ISO dates" option is set
337     * @return The formatted time
338     * @since 7299
339     */
340    public static String formatTime(Date time, int timeStyle) {
341        CheckParameterUtil.ensureParameterNotNull(time, "time");
342        return getTimeFormat(timeStyle).format(time);
343    }
344
345    /**
346     * Returns the date/time format to be used for current user, based on user preferences.
347     * @param dateStyle The date style as described in {@link DateFormat#getDateTimeInstance}. Ignored if "ISO dates" option is set
348     * @param timeStyle The time style as described in {@code DateFormat.getDateTimeInstance}. Ignored if "ISO dates" option is set
349     * @return The date/time format
350     * @since 7299
351     */
352    public static DateFormat getDateTimeFormat(int dateStyle, int timeStyle) {
353        if (Boolean.TRUE.equals(PROP_ISO_DATES.get())) {
354            // This is not strictly conform to ISO 8601. We just want to avoid US-style times such as 3.30pm
355            // and we don't want to use the 'T' separator as a space character is much more readable
356            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
357        } else {
358            return DateFormat.getDateTimeInstance(dateStyle, timeStyle, Locale.getDefault());
359        }
360    }
361
362    /**
363     * Differs from {@link DateTimeFormatter#ISO_LOCAL_DATE_TIME} by using ' ' instead of 'T' to separate date/time.
364     */
365    private static final DateTimeFormatter ISO_LOCAL_DATE_TIME = new DateTimeFormatterBuilder()
366                .parseCaseInsensitive()
367                .append(DateTimeFormatter.ISO_LOCAL_DATE)
368                .appendLiteral(' ')
369                .append(DateTimeFormatter.ISO_LOCAL_TIME)
370                .toFormatter();
371
372    /**
373     * Returns the date/time formatter to be used for current user, based on user preferences.
374     * @param dateStyle The date style. Ignored if "ISO dates" option is set.
375     * @param timeStyle The time style. Ignored if "ISO dates" option is set.
376     * @return The date/time format
377     */
378    public static DateTimeFormatter getDateTimeFormatter(FormatStyle dateStyle, FormatStyle timeStyle) {
379        DateTimeFormatter formatter = Boolean.TRUE.equals(PROP_ISO_DATES.get())
380                ? ISO_LOCAL_DATE_TIME
381                : DateTimeFormatter.ofLocalizedDateTime(dateStyle, timeStyle);
382        return formatter.withZone(ZoneId.systemDefault());
383    }
384
385    /**
386     * Formats a date/time to be displayed to current user, based on user preferences.
387     * @param datetime The date/time to display. Must not be {@code null}
388     * @param dateStyle The date style as described in {@link DateFormat#getDateTimeInstance}. Ignored if "ISO dates" option is set
389     * @param timeStyle The time style as described in {@code DateFormat.getDateTimeInstance}. Ignored if "ISO dates" option is set
390     * @return The formatted date/time
391     * @since 7299
392     */
393    public static String formatDateTime(Date datetime, int dateStyle, int timeStyle) {
394        CheckParameterUtil.ensureParameterNotNull(datetime, "datetime");
395        return getDateTimeFormat(dateStyle, timeStyle).format(datetime);
396    }
397}