为什么ISO8601 LOCALDATETIME仅适用于UTC而不适用于本地日期时间



我正在尝试将ISO8601日期的TOW格式转换为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)

这是我正在使用的模式问题吗?

谢谢!

java localdatetime类不接受时区作为参数,您需要通过ISO-8601字符串:https://docs.oracle.com/javase.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);

最新更新