【问题标题】:Error while parsing 2018-05-01T00:00:00 date using Instant.parse使用 Instant.parse 解析 2018-05-01T00:00:00 日期时出错
【发布时间】:2020-04-24 13:14:07
【问题描述】:

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

String date = "2018-05-01T00:00:00";
Instant.parse(date)

并低于错误

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)

我不能使用其他Instant,所以只能寻找解决方案!

【问题讨论】:

  • 当地时间应该在哪个时区?没有时区,您无法解析到瞬间。如果它是 UTC,你可以在解析之前简单地在字符串的末尾添加一个“Z”。
  • 我不确定,因为我是从第三方 api 响应中获得的!
  • 你应该查看第三方api的文档。
  • 2018-05-01T00:00:00 没有定义一个瞬间,一个瞬间。如果您能找出隐含的时区或 UTC 偏移量,我们可以帮助您转换为 Instant。不过,似乎一天中的时间并不重要?那么为什么不直接解析成LocalDate呢?

标签: java datetime java.time.instant


【解决方案1】:

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

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

字符串必须代表 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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 2022-01-24
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    相关资源
    最近更新 更多