DateTimeParseException,在ThreeTenABP处为索引0

问题描述 投票:2回答:2

我正在尝试使用ThreeTenABP解析时间字符串(因为我必须支持min SDK 19)。我认为字符串是ISO 8601:

20200117T172638.000Z

我收到以下异常:

org.threeten.bp.format.DateTimeParseException: Text '20200117T172638.000Z' could not be parsed at index 0

我的代码:

Instant instant = Instant.parse("20200117T172638.000Z");
long time = instant.getEpochSecond();

任何帮助表示赞赏。预先感谢。

android iso8601 datetime-parsing threetenabp
2个回答
1
投票

好像我只需要将-:添加到类似2020-01-17T17:26:38.000Z的字符串中。

太糟糕了,它不接受原始字符串。


0
投票

这有点棘手。

    DateTimeFormatter instantFormatter = DateTimeFormatter.ofPattern("uuuuMMdd'T'HHmmss.SSSX");
    String s = "20200117T172638.000Z";
    Instant instant = instantFormatter.parse(s, Instant.FROM);
    System.out.println(instant);

此片段的输出是

2020-01-17T17:26:38Z

如果Instant按您的问题工作,从纪元开始算起的秒数,所以我不再重复。

使用格式化程序来描述输入字符串的精确格式。由于没有Instant.parse方法接受DateTimeFormatter作为第二个参数,因此我们需要使用(通用)DateTimeFormatter.parse(CharSequence, TemporalQuery<T>)方法进行另一种解析。而且我们需要将查询Instant.FROM传递给该方法,因为向后移植是针对没有方法引用的Java版本开发的。 (使用Java 8和更高版本中的本地java.time,我们改为使用方法参考Instant::from。)>

我知道您的字符串是ISO 8601格式。我知道有人说java.time类无需任何显式格式化程序即可解析ISO 8601格式(我自己已经在Stack Overflow上写过很多遍了)。事实并非如此:java.time类解析没有任何显式格式化程序的ISO 8601格式的最常见的变体

。 ISO 8601具有很多语法自由,其中一些总是允许的,而某些可以在交换ISO 8601格式的各方之间达成协议。您遇到了Instant.parse()无法处理的变体,对不起。
© www.soinside.com 2019 - 2024. All rights reserved.