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.time.DateTimeException; 008import java.time.Instant; 009import java.time.ZoneId; 010import java.time.ZoneOffset; 011import java.time.ZonedDateTime; 012import java.time.format.DateTimeFormatter; 013import java.util.Date; 014import java.util.Locale; 015import java.util.TimeZone; 016import java.util.concurrent.TimeUnit; 017 018import javax.xml.datatype.DatatypeConfigurationException; 019import javax.xml.datatype.DatatypeFactory; 020 021import org.openstreetmap.josm.data.preferences.BooleanProperty; 022import org.openstreetmap.josm.tools.CheckParameterUtil; 023import org.openstreetmap.josm.tools.Logging; 024import org.openstreetmap.josm.tools.UncheckedParseException; 025 026/** 027 * A static utility class dealing with: 028 * <ul> 029 * <li>parsing XML date quickly and formatting a date to the XML UTC format regardless of current locale</li> 030 * <li>providing a single entry point for formatting dates to be displayed in JOSM GUI, based on user preferences</li> 031 * </ul> 032 * @author nenik 033 */ 034public final class DateUtils { 035 036 /** 037 * The UTC time zone. 038 */ 039 public static final TimeZone UTC = TimeZone.getTimeZone("UTC"); 040 041 /** 042 * Property to enable display of ISO dates globally. 043 * @since 7299 044 */ 045 public static final BooleanProperty PROP_ISO_DATES = new BooleanProperty("iso.dates", false); 046 047 private static final DatatypeFactory XML_DATE; 048 049 static { 050 DatatypeFactory fact = null; 051 try { 052 fact = DatatypeFactory.newInstance(); 053 } catch (DatatypeConfigurationException e) { 054 Logging.error(e); 055 } 056 XML_DATE = fact; 057 } 058 059 /** 060 * Constructs a new {@code DateUtils}. 061 */ 062 private DateUtils() { 063 // Hide default constructor for utils classes 064 } 065 066 /** 067 * Parses XML date quickly, regardless of current locale. 068 * @param str The XML date as string 069 * @return The date 070 * @throws UncheckedParseException if the date does not match any of the supported date formats 071 * @throws DateTimeException if the value of any field is out of range, or if the day-of-month is invalid for the month-year 072 */ 073 public static synchronized Date fromString(String str) { 074 return new Date(tsFromString(str)); 075 } 076 077 /** 078 * Parses XML date quickly, regardless of current locale. 079 * @param str The XML date as string 080 * @return The date in milliseconds since epoch 081 * @throws UncheckedParseException if the date does not match any of the supported date formats 082 * @throws DateTimeException if the value of any field is out of range, or if the day-of-month is invalid for the month-year 083 */ 084 public static synchronized long tsFromString(String str) { 085 // "2007-07-25T09:26:24{Z|{+|-}01[:00]}" 086 if (checkLayout(str, "xxxx-xx-xxTxx:xx:xxZ") || 087 checkLayout(str, "xxxx-xx-xxTxx:xx:xx") || 088 checkLayout(str, "xxxx:xx:xx xx:xx:xx") || 089 checkLayout(str, "xxxx-xx-xx xx:xx:xxZ") || 090 checkLayout(str, "xxxx-xx-xx xx:xx:xx UTC") || 091 checkLayout(str, "xxxx-xx-xxTxx:xx:xx+xx") || 092 checkLayout(str, "xxxx-xx-xxTxx:xx:xx-xx") || 093 checkLayout(str, "xxxx-xx-xxTxx:xx:xx+xx:00") || 094 checkLayout(str, "xxxx-xx-xxTxx:xx:xx-xx:00")) { 095 final ZonedDateTime local = ZonedDateTime.of( 096 parsePart4(str, 0), 097 parsePart2(str, 5), 098 parsePart2(str, 8), 099 parsePart2(str, 11), 100 parsePart2(str, 14), 101 parsePart2(str, 17), 102 0, 103 // consider EXIF date in default timezone 104 checkLayout(str, "xxxx:xx:xx xx:xx:xx") ? ZoneId.systemDefault() : ZoneOffset.UTC 105 ); 106 if (str.length() == 22 || str.length() == 25) { 107 final int plusHr = parsePart2(str, 20); 108 final long mul = str.charAt(19) == '+' ? -1 : 1; 109 return local.plusHours(plusHr * mul).toInstant().toEpochMilli(); 110 } 111 return local.toInstant().toEpochMilli(); 112 } else if (checkLayout(str, "xxxx-xx-xxTxx:xx:xx.xxxZ") || 113 checkLayout(str, "xxxx-xx-xxTxx:xx:xx.xxx") || 114 checkLayout(str, "xxxx:xx:xx xx:xx:xx.xxx") || 115 checkLayout(str, "xxxx-xx-xxTxx:xx:xx.xxx+xx:00") || 116 checkLayout(str, "xxxx-xx-xxTxx:xx:xx.xxx-xx:00")) { 117 final ZonedDateTime local = ZonedDateTime.of( 118 parsePart4(str, 0), 119 parsePart2(str, 5), 120 parsePart2(str, 8), 121 parsePart2(str, 11), 122 parsePart2(str, 14), 123 parsePart2(str, 17), 124 parsePart3(str, 20) * 1_000_000, 125 // consider EXIF date in default timezone 126 checkLayout(str, "xxxx:xx:xx xx:xx:xx.xxx") ? ZoneId.systemDefault() : ZoneOffset.UTC 127 ); 128 if (str.length() == 29) { 129 final int plusHr = parsePart2(str, 24); 130 final long mul = str.charAt(23) == '+' ? -1 : 1; 131 return local.plusHours(plusHr * mul).toInstant().toEpochMilli(); 132 } 133 return local.toInstant().toEpochMilli(); 134 } else { 135 // example date format "18-AUG-08 13:33:03" 136 SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yy HH:mm:ss"); 137 Date d = f.parse(str, new ParsePosition(0)); 138 if (d != null) 139 return d.getTime(); 140 } 141 142 try { 143 return XML_DATE.newXMLGregorianCalendar(str).toGregorianCalendar().getTimeInMillis(); 144 } catch (IllegalArgumentException ex) { 145 throw new UncheckedParseException("The date string (" + str + ") could not be parsed.", ex); 146 } 147 } 148 149 /** 150 * Formats a date to the XML UTC format regardless of current locale. 151 * @param timestamp number of seconds since the epoch 152 * @return The formatted date 153 * @since 14055 154 */ 155 public static String fromTimestamp(long timestamp) { 156 return fromTimestampInMillis(TimeUnit.SECONDS.toMillis(timestamp)); 157 } 158 159 /** 160 * Formats a date to the XML UTC format regardless of current locale. 161 * @param timestamp number of milliseconds since the epoch 162 * @return The formatted date 163 * @since 14434 164 */ 165 public static synchronized String fromTimestampInMillis(long timestamp) { 166 final ZonedDateTime temporal = Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.UTC); 167 return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(temporal); 168 } 169 170 /** 171 * Formats a date to the XML UTC format regardless of current locale. 172 * @param timestamp number of seconds since the epoch 173 * @return The formatted date 174 */ 175 public static synchronized String fromTimestamp(int timestamp) { 176 return fromTimestamp(Integer.toUnsignedLong(timestamp)); 177 } 178 179 /** 180 * Formats a date to the XML UTC format regardless of current locale. 181 * @param date The date to format 182 * @return The formatted date 183 */ 184 public static synchronized String fromDate(Date date) { 185 final ZonedDateTime temporal = date.toInstant().atZone(ZoneOffset.UTC); 186 return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(temporal); 187 } 188 189 /** 190 * Null-safe date cloning method. 191 * @param d date to clone, or null 192 * @return cloned date, or null 193 * @since 11878 194 */ 195 public static Date cloneDate(Date d) { 196 return d != null ? (Date) d.clone() : null; 197 } 198 199 private static boolean checkLayout(String text, String pattern) { 200 if (text.length() != pattern.length()) 201 return false; 202 for (int i = 0; i < pattern.length(); i++) { 203 char pc = pattern.charAt(i); 204 char tc = text.charAt(i); 205 if (pc == 'x' && Character.isDigit(tc)) 206 continue; 207 else if (pc == 'x' || pc != tc) 208 return false; 209 } 210 return true; 211 } 212 213 private static int num(char c) { 214 return c - '0'; 215 } 216 217 private static int parsePart2(String str, int off) { 218 return 10 * num(str.charAt(off)) + num(str.charAt(off + 1)); 219 } 220 221 private static int parsePart3(String str, int off) { 222 return 100 * num(str.charAt(off)) + 10 * num(str.charAt(off + 1)) + num(str.charAt(off + 2)); 223 } 224 225 private static int parsePart4(String str, int off) { 226 return 1000 * num(str.charAt(off)) + 100 * num(str.charAt(off + 1)) + 10 * num(str.charAt(off + 2)) + num(str.charAt(off + 3)); 227 } 228 229 /** 230 * Returns a new {@code SimpleDateFormat} for date only, according to <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a>. 231 * @return a new ISO 8601 date format, for date only. 232 * @since 7299 233 */ 234 public static SimpleDateFormat newIsoDateFormat() { 235 return new SimpleDateFormat("yyyy-MM-dd"); 236 } 237 238 /** 239 * Returns a new {@code SimpleDateFormat} for date and time, according to <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a>. 240 * @return a new ISO 8601 date format, for date and time. 241 * @since 7299 242 */ 243 public static SimpleDateFormat newIsoDateTimeFormat() { 244 return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); 245 } 246 247 /** 248 * Returns a new {@code SimpleDateFormat} for date and time, according to format used in OSM API errors. 249 * @return a new date format, for date and time, to use for OSM API error handling. 250 * @since 7299 251 */ 252 public static SimpleDateFormat newOsmApiDateTimeFormat() { 253 // Example: "2010-09-07 14:39:41 UTC". 254 // Always parsed with US locale regardless of the current locale in JOSM 255 return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.US); 256 } 257 258 /** 259 * Returns the date format to be used for current user, based on user preferences. 260 * @param dateStyle The date style as described in {@link DateFormat#getDateInstance}. Ignored if "ISO dates" option is set 261 * @return The date format 262 * @since 7299 263 */ 264 public static DateFormat getDateFormat(int dateStyle) { 265 if (PROP_ISO_DATES.get()) { 266 return newIsoDateFormat(); 267 } else { 268 return DateFormat.getDateInstance(dateStyle, Locale.getDefault()); 269 } 270 } 271 272 /** 273 * Returns the date format used for GPX waypoints. 274 * @return the date format used for GPX waypoints 275 * @since 14055 276 */ 277 public static DateFormat getGpxFormat() { 278 SimpleDateFormat result = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); 279 result.setTimeZone(UTC); 280 return result; 281 } 282 283 /** 284 * Formats a date to be displayed to current user, based on user preferences. 285 * @param date The date to display. Must not be {@code null} 286 * @param dateStyle The date style as described in {@link DateFormat#getDateInstance}. Ignored if "ISO dates" option is set 287 * @return The formatted date 288 * @since 7299 289 */ 290 public static String formatDate(Date date, int dateStyle) { 291 CheckParameterUtil.ensureParameterNotNull(date, "date"); 292 return getDateFormat(dateStyle).format(date); 293 } 294 295 /** 296 * Returns the time format to be used for current user, based on user preferences. 297 * @param timeStyle The time style as described in {@link DateFormat#getTimeInstance}. Ignored if "ISO dates" option is set 298 * @return The time format 299 * @since 7299 300 */ 301 public static DateFormat getTimeFormat(int timeStyle) { 302 if (PROP_ISO_DATES.get()) { 303 // This is not strictly conform to ISO 8601. We just want to avoid US-style times such as 3.30pm 304 return new SimpleDateFormat("HH:mm:ss"); 305 } else { 306 return DateFormat.getTimeInstance(timeStyle, Locale.getDefault()); 307 } 308 } 309 310 /** 311 * Formats a time to be displayed to current user, based on user preferences. 312 * @param time The time to display. Must not be {@code null} 313 * @param timeStyle The time style as described in {@link DateFormat#getTimeInstance}. Ignored if "ISO dates" option is set 314 * @return The formatted time 315 * @since 7299 316 */ 317 public static String formatTime(Date time, int timeStyle) { 318 CheckParameterUtil.ensureParameterNotNull(time, "time"); 319 return getTimeFormat(timeStyle).format(time); 320 } 321 322 /** 323 * Returns the date/time format to be used for current user, based on user preferences. 324 * @param dateStyle The date style as described in {@link DateFormat#getDateTimeInstance}. Ignored if "ISO dates" option is set 325 * @param timeStyle The time style as described in {@code DateFormat.getDateTimeInstance}. Ignored if "ISO dates" option is set 326 * @return The date/time format 327 * @since 7299 328 */ 329 public static DateFormat getDateTimeFormat(int dateStyle, int timeStyle) { 330 if (PROP_ISO_DATES.get()) { 331 // This is not strictly conform to ISO 8601. We just want to avoid US-style times such as 3.30pm 332 // and we don't want to use the 'T' separator as a space character is much more readable 333 return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 334 } else { 335 return DateFormat.getDateTimeInstance(dateStyle, timeStyle, Locale.getDefault()); 336 } 337 } 338 339 /** 340 * Formats a date/time to be displayed to current user, based on user preferences. 341 * @param datetime The date/time to display. Must not be {@code null} 342 * @param dateStyle The date style as described in {@link DateFormat#getDateTimeInstance}. Ignored if "ISO dates" option is set 343 * @param timeStyle The time style as described in {@code DateFormat.getDateTimeInstance}. Ignored if "ISO dates" option is set 344 * @return The formatted date/time 345 * @since 7299 346 */ 347 public static String formatDateTime(Date datetime, int dateStyle, int timeStyle) { 348 CheckParameterUtil.ensureParameterNotNull(datetime, "datetime"); 349 return getDateTimeFormat(dateStyle, timeStyle).format(datetime); 350 } 351}