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

Last change on this file since 9997 was 9997, checked in by Don-vip, 8 years ago

sonar - various fixes + javadoc

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