Java 8 Parse ISO-8601 Date Ignored Presence (or Absence) of Time Zone

My application should be able to parse the date ignoring the time zone (I always know for sure that this is UTC). The problem is that the date may appear in the following forms:

2017-09-11T12:44:07.793Z

0001-01-01T00:00:00

I can parse the first using LocalDateTime, and the second using the class Instant. Is there a way to do this using one mechanism?

PS I'm trying to avoid hardcoding Zat the end of the input line

+4
source share
2 answers

If the offset Zis optional, you can use java.time.format.DateTimeFormatterBuilderwith the optional section:

DateTimeFormatter fmt = new DateTimeFormatterBuilder()
    // date/time
    .append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
    // optional offset
    .optionalStart().appendOffsetId()
    // create formatter
    .toFormatter();

parseBest TemporalQuery, . :

Instant instant = null;
// tries to create Instant, and if it fails, try a LocalDateTime
TemporalAccessor parsed = fmt.parseBest("2017-09-11T12:44:07.793Z", Instant::from, LocalDateTime::from);
if (parsed instanceof Instant) {
    instant = (Instant) parsed;
} else if (parsed instanceof LocalDateTime) {
    // convert LocalDateTime to UTC instant
    instant = ((LocalDateTime) parsed).atOffset(ZoneOffset.UTC).toInstant();
}
System.out.println(instant); // 2017-09-11T12:44:07.793Z

(0001-01-01T00:00:00) Instant 0001-01-01T00:00:00Z.

Instant::from LocalDateTime::from, Instant. , LocalDateTime. , (, ZonedDateTime::from, ZonedDateTime, Instant toInstant()).


, UTC, :

DateTimeFormatter fmt = new DateTimeFormatterBuilder()
    // date/time
    .append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
    // optional offset
    .optionalStart().appendOffsetId()
    // create formatter with UTC
    .toFormatter().withZone(ZoneOffset.UTC);

, Instant:

System.out.println(Instant.from(fmt.parse("2017-09-11T12:44:07.793Z"))); // 2017-09-11T12:44:07.793Z
System.out.println(Instant.from(fmt.parse("0001-01-01T00:00:00"))); // 0001-01-01T00:00:00Z
+4

"parseBest", :

DateTimeFormatter parser = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss[Z]");

Temporal parsed = parser.parseBest(inputString, Instant::from, LocalDateTime::from);

, , . parseBest TemporalQuery, from, java.time. , LocalDate.from, .

lambdas instanceof, ( ):

Instant parsed = (Instant) parser.parseBest(inputString,
                    Instant::from,
                    interResult -> LocalDateTime.from(interResult).atZone(ZoneOffset.UTC).toInstant())

, , LocalDateTime ZonedDateTime, Instant, Instant.

+3

Source: https://habr.com/ru/post/1686357/


All Articles