使用 Instant.parse 解析 2018-05-01T00:00:00 日期时出错

Man*_*nki 3 java datetime java.time.instant

这是我用来使用 Instant.parse 解析字符串的代码,

String date = "2018-05-01T00:00:00";
Instant.parse(date)
Run Code Online (Sandbox Code Playgroud)

并低于错误

java.time.format.DateTimeParseException: Text '2018-05-01T00:00:00' could not be parsed at index 19
        at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
        at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
        at java.time.Instant.parse(Instant.java:395)
Run Code Online (Sandbox Code Playgroud)

我不能使用其他然后Instant所以只为它寻找解决方案!

Dea*_*ool 6

Instant.parse将只接受ISO INSTANT FORMAT 格式的字符串

从文本字符串中获取 Instant 的实例,例如 2007-12-03T10:15:30.00Z。

该字符串必须表示 UTC 中的有效时刻,并使用 DateTimeFormatter.ISO_INSTANT 进行解析。

但是您拥有的 String 代表LocalDateTime,因此将其解析为LocalDateTime然后转换为Instant

ISO-8601 日历系统中没有时区的日期时间,例如 2007-12-03T10:15:30。

LocalDateTime dateTime = LocalDateTime.parse(date);
Instant instant = dateTime.atZone(ZoneId.of("America/New_York")).toInstant();
Run Code Online (Sandbox Code Playgroud)