简体   繁体   中英

ISO8601 Date Parsing ignoring Offset

I'm trying to parse 2009-07-30T16:10:36+06:00 to a date using yyyy-MM-dd'T'HH:mm:ssXXXXX .

However the output I get appears to have not factored in the offset, as I get yyyy-MM-dd'T'HH:mm:ssXXXXX .

Any ideas what I'm missing?

final DateTimeFormatter iso8601Formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXXXX");
final ZonedDateTime zonedDateTime = ZonedDateTime.parse("2009-07-30T16:10:36+06:00", iso8601Formatter);
final String formatted = zonedDateTime.format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"));
System.out.println(formatted);

If my understanding is correct you should set the zone similar to withZoneSameInstant(ZoneId.of("UTC"))

final ZonedDateTime zonedDateTime = ZonedDateTime.parse("2009-07-30T16:10:36+06:00", DateTimeFormatter.ISO_OFFSET_DATE_TIME);

System.out.println("Without ZoneId: " + zonedDateTime.format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")));
System.out.println("With ZoneId:    " + zonedDateTime.withZoneSameInstant(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")));

Result

Without ZoneId: 30/07/2009 16:10:36
With ZoneId:    30/07/2009 10:10:36
OffsetDateTime odt = OffsetDateTime.parse("2009-07-30T16:10:36+06:00");
ZonedDateTime zdt = ZonedDateTime.ofInstant(odt.toInstant(), ZoneOffset.UTC);
// 2009-07-30T10:10:36Z

First you have no zoned date time, which would also depend on the country.

Then actually you want the Greenwich time, the UTC.

If you want the time in UTC (which is not clear from the question), then the other answers give you the correct result. Since there is no time zone (such as Europe/London Pacific/Rarotonga) in your data, there is no point in using a ZonedDateTime . OffsetDateTime is a better fit:

    final OffsetDateTime dateTime = OffsetDateTime.parse("2009-07-30T16:10:36+06:00");
    final OffsetDateTime utcDateTime = dateTime.withOffsetSameInstant(ZoneOffset.UTC);
    final String formatted = utcDateTime.format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"));
    System.out.println(formatted);

30/07/2009 10:10:36

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM