为什么iso8601 LocalDatetime仅适用于UTC而不适用于本地日期时间?

时间:2019-07-31 01:48:41

标签: java datetime iso8601

我正在尝试将iso8601日期的两种格式转换为localDateTime,但是此操作似乎无效。

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

    public class DemoIsoDate {
        public static void main(String[] args) {
              Instant instant = Instant.parse("2016-08-18T06:17:10.225Z");
              LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
              System.out.println("LocalDateTime in epoch milli : " + ldt.toEpochSecond(ZoneOffset.UTC) * 1000);

              DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mmX")
              .withZone(ZoneOffset.UTC);

              System.out.println(LocalDateTime.parse("2015-07-17T17:47:18+08:00", dtf));
        }
    }

这是堆栈跟踪:

LocalDateTime : 1471501030000 Exception in thread "main"
java.time.format.DateTimeParseException: Text '2015-07-17T17:47:18+08:00' could not be parsed at index 16
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at ca.qc.alfred.jms.reader.service.DemoIsoDate.main(DemoIsoDate.java:24)

这是我正在使用的图案问题还是什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

Java LocalDateTime类不接受时区作为参数,您需要传递ISO-8601字符串:https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html

您需要将字符串转换为LocalDateTime,然后将其转换为ZonedDateTime 示例:

LocalDateTime ldt = LocalDateTime.parse("2019-07-30T23:21");
ZoneId zoneId = ZoneId.of("America/Sao_Paulo");

ZonedDateTime zdt = ZonedDateTime.of(ldt, zoneId);