使用ThreeTenABP的索引0处的DateTimeParseException [英] DateTimeParseException at index 0 with ThreeTenABP

查看:134
本文介绍了使用ThreeTenABP的索引0处的DateTimeParseException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to parse a time string with ThreeTenABP (because I have to support min SDK 19). I think the string is 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();

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

Any help appreciated. Thanks in advance.

推荐答案

这有点棘手.

    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

2020-01-17T17:26:38Z

如果Instant可以按照您的问题进行操作,那么从纪元开始计算秒数,所以我不再重复.

Getting the seconds since the epoch out if the Instant works as in your question, so I am not repeating it.

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

Use a formatter that describes the precise format of the input string. Since there is no Instant.parse method that accepts a DateTimeFormatter as second argument, we need to do the parsing the other way around, using the (generic) DateTimeFormatter.parse(CharSequence, TemporalQuery<T>) method. And we need to pass the query Instant.FROM to that method because the backport is developed for Java versions that haven’t got method references. (Using the native java.time from Java 8 and later we would instead use the method reference Instant::from).

我知道您的字符串为ISO 8601格式.我知道有人说java.time类无需任何显式格式化程序即可解析ISO 8601格式(我自己已经在Stack Overflow上写过很多遍了).事实并非如此:java.time类解析 ISO 8601格式的最常见变体,而没有任何显式的格式化程序. ISO 8601具有相当多的语法自由,其中一些始终被允许,而另一些可以在交换ISO 8601格式的各方之间达成协议.很抱歉,您遇到了Instant.parse()无法处理的变体.

I know that your string is in ISO 8601 format. And I know that it is said that the java.time classes parse ISO 8601 format without any explicit formatter (I have myself written that many times on Stack Overflow already). It is not quite true: the classes of java.time parse the most common variants of ISO 8601 format without any explicit formatter. ISO 8601 comes with quite many freedoms of syntax, some that are always allowed and some that can optionally be agreed between parties exchanging ISO 8601 format. You have run into a variant that Instant.parse() doesn’t deal with, sorry.

这篇关于使用ThreeTenABP的索引0处的DateTimeParseException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆