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

Last change on this file since 7937 was 7299, checked in by Don-vip, 10 years ago

fix #10121 - Add a new look-and-feel preference to display ISO 8601 dates globally

  • Property svn:eol-style set to native
File size: 10.3 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;
20
21/**
22 * A static utility class dealing with:
23 * <ul>
24 * <li>parsing XML date quickly and formatting a date to the XML UTC format regardless of current locale</li>
25 * <li>providing a single entry point for formatting dates to be displayed in JOSM GUI, based on user preferences</li>
26 * </ul>
27 * @author nenik
28 */
29public final class DateUtils {
30
31 private DateUtils() {
32 // Hide default constructor for utils classes
33 }
34
35 /**
36 * Property to enable display of ISO dates globally.
37 * @since 7299
38 */
39 public static final BooleanProperty PROP_ISO_DATES = new BooleanProperty("iso.dates", false);
40
41 /**
42 * A shared instance used for conversion between individual date fields
43 * and long millis time. It is guarded against conflict by the class lock.
44 * The shared instance is used because the construction, together
45 * with the timezone lookup, is very expensive.
46 */
47 private static GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
48 private static final DatatypeFactory XML_DATE;
49
50 static {
51 calendar.setTimeInMillis(0);
52
53 DatatypeFactory fact = null;
54 try {
55 fact = DatatypeFactory.newInstance();
56 } catch(DatatypeConfigurationException ce) {
57 Main.error(ce);
58 }
59 XML_DATE = fact;
60 }
61
62 /**
63 * Parses XML date quickly, regardless of current locale.
64 * @param str The XML date as string
65 * @return The date
66 */
67 public static synchronized Date fromString(String str) {
68 // "2007-07-25T09:26:24{Z|{+|-}01:00}"
69 if (checkLayout(str, "xxxx-xx-xxTxx:xx:xxZ") ||
70 checkLayout(str, "xxxx-xx-xxTxx:xx:xx") ||
71 checkLayout(str, "xxxx-xx-xxTxx:xx:xx+xx:00") ||
72 checkLayout(str, "xxxx-xx-xxTxx:xx:xx-xx:00")) {
73 calendar.set(
74 parsePart(str, 0, 4),
75 parsePart(str, 5, 2)-1,
76 parsePart(str, 8, 2),
77 parsePart(str, 11, 2),
78 parsePart(str, 14,2),
79 parsePart(str, 17, 2));
80
81 if (str.length() == 25) {
82 int plusHr = parsePart(str, 20, 2);
83 int mul = str.charAt(19) == '+' ? -3600000 : 3600000;
84 calendar.setTimeInMillis(calendar.getTimeInMillis()+plusHr*mul);
85 }
86
87 return calendar.getTime();
88 } else if(checkLayout(str, "xxxx-xx-xxTxx:xx:xx.xxxZ") ||
89 checkLayout(str, "xxxx-xx-xxTxx:xx:xx.xxx") ||
90 checkLayout(str, "xxxx-xx-xxTxx:xx:xx.xxx+xx:00") ||
91 checkLayout(str, "xxxx-xx-xxTxx:xx:xx.xxx-xx:00")) {
92 calendar.set(
93 parsePart(str, 0, 4),
94 parsePart(str, 5, 2)-1,
95 parsePart(str, 8, 2),
96 parsePart(str, 11, 2),
97 parsePart(str, 14,2),
98 parsePart(str, 17, 2));
99 long millis = parsePart(str, 20, 3);
100 if (str.length() == 29)
101 millis += parsePart(str, 24, 2) * (str.charAt(23) == '+' ? -3600000 : 3600000);
102 calendar.setTimeInMillis(calendar.getTimeInMillis()+millis);
103
104 return calendar.getTime();
105 } else {
106 // example date format "18-AUG-08 13:33:03"
107 SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yy HH:mm:ss");
108 Date d = f.parse(str, new ParsePosition(0));
109 if(d != null)
110 return d;
111 }
112
113 try {
114 return XML_DATE.newXMLGregorianCalendar(str).toGregorianCalendar().getTime();
115 } catch (Exception ex) {
116 return new Date();
117 }
118 }
119
120 /**
121 * Formats a date to the XML UTC format regardless of current locale.
122 * @param date The date to format
123 * @return The formatted date
124 */
125 public static synchronized String fromDate(Date date) {
126 calendar.setTime(date);
127 XMLGregorianCalendar xgc = XML_DATE.newXMLGregorianCalendar(calendar);
128 if (calendar.get(Calendar.MILLISECOND) == 0) xgc.setFractionalSecond(null);
129 return xgc.toXMLFormat();
130 }
131
132 private static boolean checkLayout(String text, String pattern) {
133 if (text.length() != pattern.length()) return false;
134 for (int i=0; i<pattern.length(); i++) {
135 char pc = pattern.charAt(i);
136 char tc = text.charAt(i);
137 if(pc == 'x' && tc >= '0' && tc <= '9') continue;
138 else if(pc == 'x' || pc != tc) return false;
139 }
140 return true;
141 }
142
143 private static int parsePart(String str, int off, int len) {
144 return Integer.valueOf(str.substring(off, off+len));
145 }
146
147 /**
148 * Returns a new {@code SimpleDateFormat} for date only, according to <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a>.
149 * @return a new ISO 8601 date format, for date only.
150 * @since 7299
151 */
152 public static final SimpleDateFormat newIsoDateFormat() {
153 return new SimpleDateFormat("yyyy-MM-dd");
154 }
155
156 /**
157 * Returns a new {@code SimpleDateFormat} for date and time, according to <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a>.
158 * @return a new ISO 8601 date format, for date and time.
159 * @since 7299
160 */
161 public static final SimpleDateFormat newIsoDateTimeFormat() {
162 return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
163 }
164
165 /**
166 * Returns a new {@code SimpleDateFormat} for date and time, according to format used in OSM API errors.
167 * @return a new date format, for date and time, to use for OSM API error handling.
168 * @since 7299
169 */
170 public static final SimpleDateFormat newOsmApiDateTimeFormat() {
171 // Example: "2010-09-07 14:39:41 UTC".
172 // Always parsed with US locale regardless of the current locale in JOSM
173 return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.US);
174 }
175
176 /**
177 * Returns the date format to be used for current user, based on user preferences.
178 * @param dateStyle The date style as described in {@link DateFormat#getDateInstance}. Ignored if "ISO dates" option is set
179 * @return The date format
180 * @since 7299
181 */
182 public static final DateFormat getDateFormat(int dateStyle) {
183 if (PROP_ISO_DATES.get()) {
184 return newIsoDateFormat();
185 } else {
186 return DateFormat.getDateInstance(dateStyle, Locale.getDefault());
187 }
188 }
189
190 /**
191 * Formats a date to be displayed to current user, based on user preferences.
192 * @param date The date to display. Must not be {@code null}
193 * @param dateStyle The date style as described in {@link DateFormat#getDateInstance}. Ignored if "ISO dates" option is set
194 * @return The formatted date
195 * @since 7299
196 */
197 public static final String formatDate(Date date, int dateStyle) {
198 CheckParameterUtil.ensureParameterNotNull(date, "date");
199 return getDateFormat(dateStyle).format(date);
200 }
201
202 /**
203 * Returns the time format to be used for current user, based on user preferences.
204 * @param timeStyle The time style as described in {@link DateFormat#getTimeInstance}. Ignored if "ISO dates" option is set
205 * @return The time format
206 * @since 7299
207 */
208 public static final DateFormat getTimeFormat(int timeStyle) {
209 if (PROP_ISO_DATES.get()) {
210 // This is not strictly conform to ISO 8601. We just want to avoid US-style times such as 3.30pm
211 return new SimpleDateFormat("HH:mm:ss");
212 } else {
213 return DateFormat.getTimeInstance(timeStyle, Locale.getDefault());
214 }
215 }
216 /**
217 * Formats a time to be displayed to current user, based on user preferences.
218 * @param time The time to display. Must not be {@code null}
219 * @param timeStyle The time style as described in {@link DateFormat#getTimeInstance}. Ignored if "ISO dates" option is set
220 * @return The formatted time
221 * @since 7299
222 */
223 public static final String formatTime(Date time, int timeStyle) {
224 CheckParameterUtil.ensureParameterNotNull(time, "time");
225 return getTimeFormat(timeStyle).format(time);
226 }
227
228 /**
229 * Returns the date/time format to be used for current user, based on user preferences.
230 * @param dateStyle The date style as described in {@link DateFormat#getDateTimeInstance}. Ignored if "ISO dates" option is set
231 * @param timeStyle The time style as described in {@code DateFormat.getDateTimeInstance}. Ignored if "ISO dates" option is set
232 * @return The date/time format
233 * @since 7299
234 */
235 public static final DateFormat getDateTimeFormat(int dateStyle, int timeStyle) {
236 if (PROP_ISO_DATES.get()) {
237 // This is not strictly conform to ISO 8601. We just want to avoid US-style times such as 3.30pm
238 // and we don't want to use the 'T' separator as a space character is much more readable
239 return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
240 } else {
241 return DateFormat.getDateTimeInstance(dateStyle, timeStyle, Locale.getDefault());
242 }
243 }
244
245 /**
246 * Formats a date/time to be displayed to current user, based on user preferences.
247 * @param datetime The date/time to display. Must not be {@code null}
248 * @param dateStyle The date style as described in {@link DateFormat#getDateTimeInstance}. Ignored if "ISO dates" option is set
249 * @param timeStyle The time style as described in {@code DateFormat.getDateTimeInstance}. Ignored if "ISO dates" option is set
250 * @return The formatted date/time
251 * @since 7299
252 */
253 public static final String formatDateTime(Date datetime, int dateStyle, int timeStyle) {
254 CheckParameterUtil.ensureParameterNotNull(datetime, "datetime");
255 return getDateTimeFormat(dateStyle, timeStyle).format(datetime);
256 }
257}
Note: See TracBrowser for help on using the repository browser.