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

Last change on this file since 8513 was 8510, checked in by Don-vip, 9 years ago

checkstyle: enable relevant whitespace checks and fix them

  • 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-xx xx:xx:xx UTC") ||
72 checkLayout(str, "xxxx-xx-xxTxx:xx:xx+xx:00") ||
73 checkLayout(str, "xxxx-xx-xxTxx:xx:xx-xx:00")) {
74 calendar.set(
75 parsePart(str, 0, 4),
76 parsePart(str, 5, 2)-1,
77 parsePart(str, 8, 2),
78 parsePart(str, 11, 2),
79 parsePart(str, 14, 2),
80 parsePart(str, 17, 2));
81
82 if (str.length() == 25) {
83 int plusHr = parsePart(str, 20, 2);
84 int mul = str.charAt(19) == '+' ? -3600000 : 3600000;
85 calendar.setTimeInMillis(calendar.getTimeInMillis()+plusHr*mul);
86 }
87
88 return calendar.getTime();
89 } else if (checkLayout(str, "xxxx-xx-xxTxx:xx:xx.xxxZ") ||
90 checkLayout(str, "xxxx-xx-xxTxx:xx:xx.xxx") ||
91 checkLayout(str, "xxxx-xx-xxTxx:xx:xx.xxx+xx:00") ||
92 checkLayout(str, "xxxx-xx-xxTxx:xx:xx.xxx-xx:00")) {
93 calendar.set(
94 parsePart(str, 0, 4),
95 parsePart(str, 5, 2)-1,
96 parsePart(str, 8, 2),
97 parsePart(str, 11, 2),
98 parsePart(str, 14, 2),
99 parsePart(str, 17, 2));
100 long millis = parsePart(str, 20, 3);
101 if (str.length() == 29)
102 millis += parsePart(str, 24, 2) * (str.charAt(23) == '+' ? -3600000 : 3600000);
103 calendar.setTimeInMillis(calendar.getTimeInMillis()+millis);
104
105 return calendar.getTime();
106 } else {
107 // example date format "18-AUG-08 13:33:03"
108 SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yy HH:mm:ss");
109 Date d = f.parse(str, new ParsePosition(0));
110 if (d != null)
111 return d;
112 }
113
114 try {
115 return XML_DATE.newXMLGregorianCalendar(str).toGregorianCalendar().getTime();
116 } catch (Exception ex) {
117 return new Date();
118 }
119 }
120
121 /**
122 * Formats a date to the XML UTC format regardless of current locale.
123 * @param date The date to format
124 * @return The formatted date
125 */
126 public static synchronized String fromDate(Date date) {
127 calendar.setTime(date);
128 XMLGregorianCalendar xgc = XML_DATE.newXMLGregorianCalendar(calendar);
129 if (calendar.get(Calendar.MILLISECOND) == 0) xgc.setFractionalSecond(null);
130 return xgc.toXMLFormat();
131 }
132
133 private static boolean checkLayout(String text, String pattern) {
134 if (text.length() != pattern.length()) return false;
135 for (int i = 0; i < pattern.length(); i++) {
136 char pc = pattern.charAt(i);
137 char tc = text.charAt(i);
138 if (pc == 'x' && tc >= '0' && tc <= '9') continue;
139 else if (pc == 'x' || pc != tc) return false;
140 }
141 return true;
142 }
143
144 private static int parsePart(String str, int off, int len) {
145 return Integer.parseInt(str.substring(off, off+len));
146 }
147
148 /**
149 * Returns a new {@code SimpleDateFormat} for date only, according to <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a>.
150 * @return a new ISO 8601 date format, for date only.
151 * @since 7299
152 */
153 public static SimpleDateFormat newIsoDateFormat() {
154 return new SimpleDateFormat("yyyy-MM-dd");
155 }
156
157 /**
158 * Returns a new {@code SimpleDateFormat} for date and time, according to <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a>.
159 * @return a new ISO 8601 date format, for date and time.
160 * @since 7299
161 */
162 public static SimpleDateFormat newIsoDateTimeFormat() {
163 return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
164 }
165
166 /**
167 * Returns a new {@code SimpleDateFormat} for date and time, according to format used in OSM API errors.
168 * @return a new date format, for date and time, to use for OSM API error handling.
169 * @since 7299
170 */
171 public static SimpleDateFormat newOsmApiDateTimeFormat() {
172 // Example: "2010-09-07 14:39:41 UTC".
173 // Always parsed with US locale regardless of the current locale in JOSM
174 return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.US);
175 }
176
177 /**
178 * Returns the date format to be used for current user, based on user preferences.
179 * @param dateStyle The date style as described in {@link DateFormat#getDateInstance}. Ignored if "ISO dates" option is set
180 * @return The date format
181 * @since 7299
182 */
183 public static DateFormat getDateFormat(int dateStyle) {
184 if (PROP_ISO_DATES.get()) {
185 return newIsoDateFormat();
186 } else {
187 return DateFormat.getDateInstance(dateStyle, Locale.getDefault());
188 }
189 }
190
191 /**
192 * Formats a date to be displayed to current user, based on user preferences.
193 * @param date The date to display. Must not be {@code null}
194 * @param dateStyle The date style as described in {@link DateFormat#getDateInstance}. Ignored if "ISO dates" option is set
195 * @return The formatted date
196 * @since 7299
197 */
198 public static String formatDate(Date date, int dateStyle) {
199 CheckParameterUtil.ensureParameterNotNull(date, "date");
200 return getDateFormat(dateStyle).format(date);
201 }
202
203 /**
204 * Returns the time format to be used for current user, based on user preferences.
205 * @param timeStyle The time style as described in {@link DateFormat#getTimeInstance}. Ignored if "ISO dates" option is set
206 * @return The time format
207 * @since 7299
208 */
209 public static DateFormat getTimeFormat(int timeStyle) {
210 if (PROP_ISO_DATES.get()) {
211 // This is not strictly conform to ISO 8601. We just want to avoid US-style times such as 3.30pm
212 return new SimpleDateFormat("HH:mm:ss");
213 } else {
214 return DateFormat.getTimeInstance(timeStyle, Locale.getDefault());
215 }
216 }
217 /**
218 * Formats a time to be displayed to current user, based on user preferences.
219 * @param time The time to display. Must not be {@code null}
220 * @param timeStyle The time style as described in {@link DateFormat#getTimeInstance}. Ignored if "ISO dates" option is set
221 * @return The formatted time
222 * @since 7299
223 */
224 public static String formatTime(Date time, int timeStyle) {
225 CheckParameterUtil.ensureParameterNotNull(time, "time");
226 return getTimeFormat(timeStyle).format(time);
227 }
228
229 /**
230 * Returns the date/time format to be used for current user, based on user preferences.
231 * @param dateStyle The date style as described in {@link DateFormat#getDateTimeInstance}. Ignored if "ISO dates" option is set
232 * @param timeStyle The time style as described in {@code DateFormat.getDateTimeInstance}. Ignored if "ISO dates" option is set
233 * @return The date/time format
234 * @since 7299
235 */
236 public static DateFormat getDateTimeFormat(int dateStyle, int timeStyle) {
237 if (PROP_ISO_DATES.get()) {
238 // This is not strictly conform to ISO 8601. We just want to avoid US-style times such as 3.30pm
239 // and we don't want to use the 'T' separator as a space character is much more readable
240 return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
241 } else {
242 return DateFormat.getDateTimeInstance(dateStyle, timeStyle, Locale.getDefault());
243 }
244 }
245
246 /**
247 * Formats a date/time to be displayed to current user, based on user preferences.
248 * @param datetime The date/time to display. Must not be {@code null}
249 * @param dateStyle The date style as described in {@link DateFormat#getDateTimeInstance}. Ignored if "ISO dates" option is set
250 * @param timeStyle The time style as described in {@code DateFormat.getDateTimeInstance}. Ignored if "ISO dates" option is set
251 * @return The formatted date/time
252 * @since 7299
253 */
254 public static String formatDateTime(Date datetime, int dateStyle, int timeStyle) {
255 CheckParameterUtil.ensureParameterNotNull(datetime, "datetime");
256 return getDateTimeFormat(dateStyle, timeStyle).format(datetime);
257 }
258}
Note: See TracBrowser for help on using the repository browser.