简体   繁体   English

ISO8601日期解析忽略偏移量

[英]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 . 我正在尝试使用yyyy-MM-dd'T'HH:mm:ssXXXXX2009-07-30T16:10:36+06:00解析为一个日期。

However the output I get appears to have not factored in the offset, as I get yyyy-MM-dd'T'HH:mm:ssXXXXX . 但是我得到的输出似乎没有考虑偏移量,因为我得到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")) 如果我的理解是正确的,则应将zone设置为与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. 那么实际上您想要格林威治时间(UTC)。

If you want the time in UTC (which is not clear from the question), then the other answers give you the correct result. 如果您想使用UTC时间(问题尚不清楚),那么其他答案将为您提供正确的结果。 Since there is no time zone (such as Europe/London Pacific/Rarotonga) in your data, there is no point in using a ZonedDateTime . 由于您的数据中没有时区(例如欧洲/伦敦太平洋/拉罗通加),因此使用ZonedDateTime没有意义。 OffsetDateTime is a better fit: OffsetDateTime更适合:

    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 30/07/2009 10:10:36

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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