dmachop
dmachop

Reputation: 884

Java8 parse date or date time format for a given string

I have a file that can have a date modified value with the format of a date or date time. I used to parse the value as:

String t = "2012-01-05T21:21:52.834Z";
logger.info(ZonedDateTime.parse(t).toEpochSecond() * 1000);

Now, the string could also be

t = "2012-01-05";

which threw an error

Exception in thread "main" java.time.format.DateTimeParseException: Text '2012-01-05' could not be parsed at index 10 at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source)

If I do this string with (Reference)

LocalDate date = LocalDate.parse(t, DateTimeFormatter.ISO_DATE);
logger.info(date.atStartOfDay(ZoneId.of("UTC")).toEpochSecond() * 1000);

This would work. However, as I have mentioned that string could be either of these types, how can I identify the format and then get the millis accordingly?

Upvotes: 3

Views: 3110

Answers (1)

Tunaki
Tunaki

Reputation: 137309

A possible solution is to use optional pattern with default values. Using a DateTimeFormatterBuilder, you can append the wanted pattern with the time part in an optional section, i.e. surrounded by [...]. In the case where the fields are absent, we provide default values by setting them to 0. The OFFSET_SECONDS field to 0 represents no offset from UTC.

public static void main(String[] args) {
    String[] dates = { "2012-01-05T21:21:52.834Z", "2012-01-05" };

    DateTimeFormatter formatter = 
        new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd['T'HH:mm:ss.SSSz]")
                                      .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
                                      .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
                                      .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
                                      .parseDefaulting(ChronoField.NANO_OF_SECOND, 0)
                                      .parseDefaulting(ChronoField.OFFSET_SECONDS, 0)
                                      .toFormatter();
    for (String date : dates) {
        ZonedDateTime zonedDateTime = ZonedDateTime.parse(date, formatter);
        System.out.println(zonedDateTime.toEpochSecond() * 1000);
    }
}

Upvotes: 8

Related Questions