1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.tools.date;
|
---|
3 |
|
---|
4 | import java.text.DateFormat;
|
---|
5 | import java.text.ParsePosition;
|
---|
6 | import java.text.SimpleDateFormat;
|
---|
7 | import java.util.Calendar;
|
---|
8 | import java.util.Date;
|
---|
9 | import java.util.GregorianCalendar;
|
---|
10 | import java.util.Locale;
|
---|
11 | import java.util.TimeZone;
|
---|
12 |
|
---|
13 | import javax.xml.datatype.DatatypeConfigurationException;
|
---|
14 | import javax.xml.datatype.DatatypeFactory;
|
---|
15 | import javax.xml.datatype.XMLGregorianCalendar;
|
---|
16 |
|
---|
17 | import org.openstreetmap.josm.Main;
|
---|
18 | import org.openstreetmap.josm.data.preferences.BooleanProperty;
|
---|
19 | import org.openstreetmap.josm.tools.CheckParameterUtil;
|
---|
20 | import org.openstreetmap.josm.tools.UncheckedParseException;
|
---|
21 |
|
---|
22 | /**
|
---|
23 | * A static utility class dealing with:
|
---|
24 | * <ul>
|
---|
25 | * <li>parsing XML date quickly and formatting a date to the XML UTC format regardless of current locale</li>
|
---|
26 | * <li>providing a single entry point for formatting dates to be displayed in JOSM GUI, based on user preferences</li>
|
---|
27 | * </ul>
|
---|
28 | * @author nenik
|
---|
29 | */
|
---|
30 | public final class DateUtils {
|
---|
31 |
|
---|
32 | private DateUtils() {
|
---|
33 | // Hide default constructor for utils classes
|
---|
34 | }
|
---|
35 |
|
---|
36 | /**
|
---|
37 | * Property to enable display of ISO dates globally.
|
---|
38 | * @since 7299
|
---|
39 | */
|
---|
40 | public static final BooleanProperty PROP_ISO_DATES = new BooleanProperty("iso.dates", false);
|
---|
41 |
|
---|
42 | /**
|
---|
43 | * A shared instance used for conversion between individual date fields
|
---|
44 | * and long millis time. It is guarded against conflict by the class lock.
|
---|
45 | * The shared instance is used because the construction, together
|
---|
46 | * with the timezone lookup, is very expensive.
|
---|
47 | */
|
---|
48 | private static final GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
|
---|
49 | private static final GregorianCalendar calendarLocale = new GregorianCalendar(TimeZone.getDefault());
|
---|
50 | private static final DatatypeFactory XML_DATE;
|
---|
51 |
|
---|
52 | static {
|
---|
53 | calendar.setTimeInMillis(0);
|
---|
54 | calendarLocale.setTimeInMillis(0);
|
---|
55 |
|
---|
56 | DatatypeFactory fact = null;
|
---|
57 | try {
|
---|
58 | fact = DatatypeFactory.newInstance();
|
---|
59 | } catch (DatatypeConfigurationException ce) {
|
---|
60 | Main.error(ce);
|
---|
61 | }
|
---|
62 | XML_DATE = fact;
|
---|
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) throws UncheckedParseException {
|
---|
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) throws UncheckedParseException {
|
---|
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:xx UTC") ||
|
---|
87 | checkLayout(str, "xxxx-xx-xxTxx:xx:xx+xx:00") ||
|
---|
88 | checkLayout(str, "xxxx-xx-xxTxx:xx:xx-xx:00")) {
|
---|
89 | final Calendar c = checkLayout(str, "xxxx:xx:xx xx:xx:xx") ? calendarLocale : calendar; // consider EXIF date in default timezone
|
---|
90 | c.set(
|
---|
91 | parsePart4(str, 0),
|
---|
92 | parsePart2(str, 5)-1,
|
---|
93 | parsePart2(str, 8),
|
---|
94 | parsePart2(str, 11),
|
---|
95 | parsePart2(str, 14),
|
---|
96 | parsePart2(str, 17));
|
---|
97 |
|
---|
98 | if (str.length() == 25) {
|
---|
99 | int plusHr = parsePart2(str, 20);
|
---|
100 | int mul = str.charAt(19) == '+' ? -3600000 : 3600000;
|
---|
101 | return c.getTimeInMillis()+plusHr*mul;
|
---|
102 | }
|
---|
103 |
|
---|
104 | return c.getTimeInMillis();
|
---|
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 Calendar c = checkLayout(str, "xxxx:xx:xx xx:xx:xx.xxx") ? calendarLocale : calendar; // consider EXIF date in default timezone
|
---|
111 | c.set(
|
---|
112 | parsePart4(str, 0),
|
---|
113 | parsePart2(str, 5)-1,
|
---|
114 | parsePart2(str, 8),
|
---|
115 | parsePart2(str, 11),
|
---|
116 | parsePart2(str, 14),
|
---|
117 | parsePart2(str, 17));
|
---|
118 | long millis = parsePart3(str, 20);
|
---|
119 | if (str.length() == 29) {
|
---|
120 | millis += parsePart2(str, 24) * (str.charAt(23) == '+' ? -3600000 : 3600000);
|
---|
121 | }
|
---|
122 |
|
---|
123 | return c.getTimeInMillis() + millis;
|
---|
124 | } else {
|
---|
125 | // example date format "18-AUG-08 13:33:03"
|
---|
126 | SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yy HH:mm:ss");
|
---|
127 | Date d = f.parse(str, new ParsePosition(0));
|
---|
128 | if (d != null)
|
---|
129 | return d.getTime();
|
---|
130 | }
|
---|
131 |
|
---|
132 | try {
|
---|
133 | return XML_DATE.newXMLGregorianCalendar(str).toGregorianCalendar().getTimeInMillis();
|
---|
134 | } catch (Exception ex) {
|
---|
135 | throw new UncheckedParseException("The date string (" + str + ") could not be parsed.");
|
---|
136 | }
|
---|
137 | }
|
---|
138 |
|
---|
139 | private static String toXmlFormat(GregorianCalendar cal) {
|
---|
140 | XMLGregorianCalendar xgc = XML_DATE.newXMLGregorianCalendar(cal);
|
---|
141 | if (cal.get(Calendar.MILLISECOND) == 0) {
|
---|
142 | xgc.setFractionalSecond(null);
|
---|
143 | }
|
---|
144 | return xgc.toXMLFormat();
|
---|
145 | }
|
---|
146 |
|
---|
147 | /**
|
---|
148 | * Formats a date to the XML UTC format regardless of current locale.
|
---|
149 | * @param timestamp number of seconds since the epoch
|
---|
150 | * @return The formatted date
|
---|
151 | */
|
---|
152 | public static synchronized String fromTimestamp(int timestamp) {
|
---|
153 | calendar.setTimeInMillis(timestamp * 1000L);
|
---|
154 | return toXmlFormat(calendar);
|
---|
155 | }
|
---|
156 |
|
---|
157 | /**
|
---|
158 | * Formats a date to the XML UTC format regardless of current locale.
|
---|
159 | * @param date The date to format
|
---|
160 | * @return The formatted date
|
---|
161 | */
|
---|
162 | public static synchronized String fromDate(Date date) {
|
---|
163 | calendar.setTime(date);
|
---|
164 | return toXmlFormat(calendar);
|
---|
165 | }
|
---|
166 |
|
---|
167 | private static boolean checkLayout(String text, String pattern) {
|
---|
168 | if (text.length() != pattern.length()) return false;
|
---|
169 | for (int i = 0; i < pattern.length(); i++) {
|
---|
170 | char pc = pattern.charAt(i);
|
---|
171 | char tc = text.charAt(i);
|
---|
172 | if (pc == 'x' && tc >= '0' && tc <= '9') continue;
|
---|
173 | else if (pc == 'x' || pc != tc) return false;
|
---|
174 | }
|
---|
175 | return true;
|
---|
176 | }
|
---|
177 |
|
---|
178 | private static int num(char c) {
|
---|
179 | return c - '0';
|
---|
180 | }
|
---|
181 |
|
---|
182 | private static int parsePart2(String str, int off) {
|
---|
183 | return 10 * num(str.charAt(off)) + num(str.charAt(off + 1));
|
---|
184 | }
|
---|
185 |
|
---|
186 | private static int parsePart3(String str, int off) {
|
---|
187 | return 100 * num(str.charAt(off)) + 10 * num(str.charAt(off + 1)) + num(str.charAt(off + 2));
|
---|
188 | }
|
---|
189 |
|
---|
190 | private static int parsePart4(String str, int off) {
|
---|
191 | return 1000 * num(str.charAt(off)) + 100 * num(str.charAt(off + 1)) + 10 * num(str.charAt(off + 2)) + num(str.charAt(off + 3));
|
---|
192 | }
|
---|
193 |
|
---|
194 | /**
|
---|
195 | * Returns a new {@code SimpleDateFormat} for date only, according to <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a>.
|
---|
196 | * @return a new ISO 8601 date format, for date only.
|
---|
197 | * @since 7299
|
---|
198 | */
|
---|
199 | public static SimpleDateFormat newIsoDateFormat() {
|
---|
200 | return new SimpleDateFormat("yyyy-MM-dd");
|
---|
201 | }
|
---|
202 |
|
---|
203 | /**
|
---|
204 | * Returns a new {@code SimpleDateFormat} for date and time, according to <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a>.
|
---|
205 | * @return a new ISO 8601 date format, for date and time.
|
---|
206 | * @since 7299
|
---|
207 | */
|
---|
208 | public static SimpleDateFormat newIsoDateTimeFormat() {
|
---|
209 | return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
|
---|
210 | }
|
---|
211 |
|
---|
212 | /**
|
---|
213 | * Returns a new {@code SimpleDateFormat} for date and time, according to format used in OSM API errors.
|
---|
214 | * @return a new date format, for date and time, to use for OSM API error handling.
|
---|
215 | * @since 7299
|
---|
216 | */
|
---|
217 | public static SimpleDateFormat newOsmApiDateTimeFormat() {
|
---|
218 | // Example: "2010-09-07 14:39:41 UTC".
|
---|
219 | // Always parsed with US locale regardless of the current locale in JOSM
|
---|
220 | return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.US);
|
---|
221 | }
|
---|
222 |
|
---|
223 | /**
|
---|
224 | * Returns the date format to be used for current user, based on user preferences.
|
---|
225 | * @param dateStyle The date style as described in {@link DateFormat#getDateInstance}. Ignored if "ISO dates" option is set
|
---|
226 | * @return The date format
|
---|
227 | * @since 7299
|
---|
228 | */
|
---|
229 | public static DateFormat getDateFormat(int dateStyle) {
|
---|
230 | if (PROP_ISO_DATES.get()) {
|
---|
231 | return newIsoDateFormat();
|
---|
232 | } else {
|
---|
233 | return DateFormat.getDateInstance(dateStyle, Locale.getDefault());
|
---|
234 | }
|
---|
235 | }
|
---|
236 |
|
---|
237 | /**
|
---|
238 | * Formats a date to be displayed to current user, based on user preferences.
|
---|
239 | * @param date The date to display. Must not be {@code null}
|
---|
240 | * @param dateStyle The date style as described in {@link DateFormat#getDateInstance}. Ignored if "ISO dates" option is set
|
---|
241 | * @return The formatted date
|
---|
242 | * @since 7299
|
---|
243 | */
|
---|
244 | public static String formatDate(Date date, int dateStyle) {
|
---|
245 | CheckParameterUtil.ensureParameterNotNull(date, "date");
|
---|
246 | return getDateFormat(dateStyle).format(date);
|
---|
247 | }
|
---|
248 |
|
---|
249 | /**
|
---|
250 | * Returns the time format to be used for current user, based on user preferences.
|
---|
251 | * @param timeStyle The time style as described in {@link DateFormat#getTimeInstance}. Ignored if "ISO dates" option is set
|
---|
252 | * @return The time format
|
---|
253 | * @since 7299
|
---|
254 | */
|
---|
255 | public static DateFormat getTimeFormat(int timeStyle) {
|
---|
256 | if (PROP_ISO_DATES.get()) {
|
---|
257 | // This is not strictly conform to ISO 8601. We just want to avoid US-style times such as 3.30pm
|
---|
258 | return new SimpleDateFormat("HH:mm:ss");
|
---|
259 | } else {
|
---|
260 | return DateFormat.getTimeInstance(timeStyle, Locale.getDefault());
|
---|
261 | }
|
---|
262 | }
|
---|
263 |
|
---|
264 | /**
|
---|
265 | * Formats a time to be displayed to current user, based on user preferences.
|
---|
266 | * @param time The time to display. Must not be {@code null}
|
---|
267 | * @param timeStyle The time style as described in {@link DateFormat#getTimeInstance}. Ignored if "ISO dates" option is set
|
---|
268 | * @return The formatted time
|
---|
269 | * @since 7299
|
---|
270 | */
|
---|
271 | public static String formatTime(Date time, int timeStyle) {
|
---|
272 | CheckParameterUtil.ensureParameterNotNull(time, "time");
|
---|
273 | return getTimeFormat(timeStyle).format(time);
|
---|
274 | }
|
---|
275 |
|
---|
276 | /**
|
---|
277 | * Returns the date/time format to be used for current user, based on user preferences.
|
---|
278 | * @param dateStyle The date style as described in {@link DateFormat#getDateTimeInstance}. Ignored if "ISO dates" option is set
|
---|
279 | * @param timeStyle The time style as described in {@code DateFormat.getDateTimeInstance}. Ignored if "ISO dates" option is set
|
---|
280 | * @return The date/time format
|
---|
281 | * @since 7299
|
---|
282 | */
|
---|
283 | public static DateFormat getDateTimeFormat(int dateStyle, int timeStyle) {
|
---|
284 | if (PROP_ISO_DATES.get()) {
|
---|
285 | // This is not strictly conform to ISO 8601. We just want to avoid US-style times such as 3.30pm
|
---|
286 | // and we don't want to use the 'T' separator as a space character is much more readable
|
---|
287 | return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
---|
288 | } else {
|
---|
289 | return DateFormat.getDateTimeInstance(dateStyle, timeStyle, Locale.getDefault());
|
---|
290 | }
|
---|
291 | }
|
---|
292 |
|
---|
293 | /**
|
---|
294 | * Formats a date/time to be displayed to current user, based on user preferences.
|
---|
295 | * @param datetime The date/time to display. Must not be {@code null}
|
---|
296 | * @param dateStyle The date style as described in {@link DateFormat#getDateTimeInstance}. Ignored if "ISO dates" option is set
|
---|
297 | * @param timeStyle The time style as described in {@code DateFormat.getDateTimeInstance}. Ignored if "ISO dates" option is set
|
---|
298 | * @return The formatted date/time
|
---|
299 | * @since 7299
|
---|
300 | */
|
---|
301 | public static String formatDateTime(Date datetime, int dateStyle, int timeStyle) {
|
---|
302 | CheckParameterUtil.ensureParameterNotNull(datetime, "datetime");
|
---|
303 | return getDateTimeFormat(dateStyle, timeStyle).format(datetime);
|
---|
304 | }
|
---|
305 |
|
---|
306 | /**
|
---|
307 | * Allows to override the timezone for unit tests.
|
---|
308 | * @param zone the timezone to use
|
---|
309 | */
|
---|
310 | protected static void setTimeZone(TimeZone zone) {
|
---|
311 | calendarLocale.setTimeZone(zone);
|
---|
312 | }
|
---|
313 | }
|
---|