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.Instant;
008import java.time.ZoneId;
009import java.time.ZoneOffset;
010import java.time.ZonedDateTime;
011import java.time.format.DateTimeFormatter;
012import java.util.Date;
013import java.util.Locale;
014import java.util.TimeZone;
015import java.util.concurrent.TimeUnit;
016
017import javax.xml.datatype.DatatypeConfigurationException;
018import javax.xml.datatype.DatatypeFactory;
019
020import org.openstreetmap.josm.Main;
021import org.openstreetmap.josm.data.preferences.BooleanProperty;
022import org.openstreetmap.josm.tools.CheckParameterUtil;
023import org.openstreetmap.josm.tools.UncheckedParseException;
024
025/**
026 * A static utility class dealing with:
027 * <ul>
028 * <li>parsing XML date quickly and formatting a date to the XML UTC format regardless of current locale</li>
029 * <li>providing a single entry point for formatting dates to be displayed in JOSM GUI, based on user preferences</li>
030 * </ul>
031 * @author nenik
032 */
033public final class DateUtils {
034
035    /**
036     * The UTC time zone.
037     */
038    public static final TimeZone UTC = TimeZone.getTimeZone("UTC");
039
040    /**
041     * Property to enable display of ISO dates globally.
042     * @since 7299
043     */
044    public static final BooleanProperty PROP_ISO_DATES = new BooleanProperty("iso.dates", false);
045
046    private static final DatatypeFactory XML_DATE;
047
048    static {
049        DatatypeFactory fact = null;
050        try {
051            fact = DatatypeFactory.newInstance();
052        } catch (DatatypeConfigurationException ce) {
053            Main.error(ce);
054        }
055        XML_DATE = fact;
056    }
057
058    protected DateUtils() {
059        // Hide default constructor for utils classes
060    }
061
062    /**
063     * Parses XML date quickly, regardless of current locale.
064     * @param str The XML date as string
065     * @return The date
066     * @throws UncheckedParseException if the date does not match any of the supported date formats
067     */
068    public static synchronized Date fromString(String str) {
069        return new Date(tsFromString(str));
070    }
071
072    /**
073     * Parses XML date quickly, regardless of current locale.
074     * @param str The XML date as string
075     * @return The date in milliseconds since epoch
076     * @throws UncheckedParseException if the date does not match any of the supported date formats
077     */
078    public static synchronized long tsFromString(String str) {
079        // "2007-07-25T09:26:24{Z|{+|-}01[:00]}"
080        if (checkLayout(str, "xxxx-xx-xxTxx:xx:xxZ") ||
081                checkLayout(str, "xxxx-xx-xxTxx:xx:xx") ||
082                checkLayout(str, "xxxx:xx:xx xx:xx:xx") ||
083                checkLayout(str, "xxxx-xx-xx xx:xx:xx UTC") ||
084                checkLayout(str, "xxxx-xx-xxTxx:xx:xx+xx") ||
085                checkLayout(str, "xxxx-xx-xxTxx:xx:xx-xx") ||
086                checkLayout(str, "xxxx-xx-xxTxx:xx:xx+xx:00") ||
087                checkLayout(str, "xxxx-xx-xxTxx:xx:xx-xx:00")) {
088            final ZonedDateTime local = ZonedDateTime.of(
089                parsePart4(str, 0),
090                parsePart2(str, 5),
091                parsePart2(str, 8),
092                parsePart2(str, 11),
093                parsePart2(str, 14),
094                parsePart2(str, 17),
095                0,
096                // consider EXIF date in default timezone
097                checkLayout(str, "xxxx:xx:xx xx:xx:xx") ? ZoneId.systemDefault() : ZoneOffset.UTC
098            );
099            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}