Class DateTimeFormats

java.lang.Object
com.google.mu.time.DateTimeFormats

public final class DateTimeFormats extends Object
Utility class with one-stop Instant and ZonedDateTime parsing for all common date time strings, without needing a DateTimeFormatter:

 Instant timestamp = DateTimeFormats.parseToInstant(timestampString);
 ZonedDateTime dateTime = DateTimeFormats.parseZonedDateTime(dateTimeString);
 

For more flexible use cases, where you might want to reuse or conform to a format known at compile-time, the DateTimeFormatter can be inferred from an example date/time/datetime string (similar to the golang time library style).

For example:


 private static final DateTimeFormatter DATE_TIME_FORMATTER =
     DateTimeFormats.formatOf("2023-12-09 10:00:00.12345 America/Los_Angeles");
 private static final DateTimeFormatter USING_ZONE_OFFSET =
     DateTimeFormats.formatOf("2023-12-09 10:00:00+08:00");
 private static final DateTimeFormatter ISO_FORMATTER =
     DateTimeFormats.formatOf("2023-12-09T10:00:00.12345[Europe/Paris]");
 private static final DateTimeFormatter WITH_DAY_OF_WEEK =
     DateTimeFormats.formatOf("2023/12/09 Sat 10:00+08:00");
 

Most ISO 8601 formats are supported, except BASIC_ISO_DATE, ISO_WEEK_DATE ('2012-W48-6') and ISO_ORDINAL_DATE ('2012-337'), which are rarely used.

For the date part of custom patterns, ambiguous examples like 10/12/2024 or 1/2/yyyy are not supported. You should use unambiguous examples like 10/30/2024 (which results in "MM/dd/yyyy"} or 30/1/2024 (which results in "dd/M/yyyy}. In addition, localized month names such as Jan or March are used, all natural orders ( year month day, month day year or day month year) are supported.

For the time part of custom patterns, only HH:mm, HH:mm:ss and HH:mm:ss.S variants are supported (the S can be 1 to 9 digits). AM/PM and 12-hour numbers are not supported. Though you can explicitly specify them together with placeholders (see below).

If the variant of the date time pattern you need exceeds the out-of-box support, you can explicitly mix the DateTimeFormatter specifiers with example placeholders (between a pair of pointy brackets) to be translated.

For example the following code uses the dd, MM and yyyy specifiers as is but translates the Tue and America/New_York example snippets into E and VV specifiers respectively. It will then parse and format to datetime strings like "Fri, 20 Oct 2023 10:30:59.123 Europe/Paris".


 private static final DateTimeFormatter FORMATTER =
     formatOf("<Tue>, dd MM yyyy HH:mm:ss.SSS <America/New_York>");
 

i18n isn't supported.

Since:
7.1