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