首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ThreeTenABP DateTime解析器为yyyy:mm:ss甲酸盐提供异常

ThreeTenABP DateTime解析器为yyyy:mm:ss甲酸盐提供异常
EN

Stack Overflow用户
提问于 2020-09-23 06:21:22
回答 1查看 416关注 0票数 2

我需要将dateTime String转换为millis,为此我使用ThreeTenABP,但是OffSetDateTime.parse无法解析用于ex的dateTime String"2020-08-14T20:05:00",并给出以下异常。

代码语言:javascript
复制
Caused by: org.threeten.bp.format.DateTimeParseException:  
Text '2020-09-22T20:35:00' could not be parsed:  
Unable to obtain OffsetDateTime from TemporalAccessor:  
DateTimeBuilder[, ISO, null, 2020-09-22, 20:35], type org.threeten.bp.format.DateTimeBuilder

我已经搜索过类似的问题,但没有找到确切的解决办法。

下面是我在Kotlin中使用的代码。

代码语言:javascript
复制
val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss",
                                                                Locale.ROOT)
val givenDateString = event?.eventDateTime
val timeInMillis = OffsetDateTime.parse(givenDateString, formatter)
                                    .toInstant()
                                    .toEpochMilli()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-23 06:46:46

问题是String中缺少的偏移量,您正试图将其解析为OffsetDateTime。一个OffsetDateTime不能在没有ZoneOffset的情况下创建,但是不能从这个String派生出任何ZoneOffset (人们可以猜测它是UTC,但是猜测在这种情况下是不合适的)。

您可以将String解析为LocalDateTime (一天中的日期和时间的表示而没有区域或偏移),然后添加/附加所需的偏移量。您甚至不需要自定义DateTimeFormatter,因为您的String是ISO格式的,可以使用默认的内置格式化程序进行解析:

代码语言:javascript
复制
fun main() {
    // example String
    val givenDateString = "2020-09-22T20:35:00"
    // determine the zone id of the device (you can alternatively set a fix one here)
    val localZoneId: ZoneId = ZoneId.systemDefault()
    // parse the String to a LocalDateTime
    val localDateTime = LocalDateTime.parse(givenDateString)
    // then create a ZonedDateTime by adding the zone id and convert it to an OffsetDateTime
    val odt: OffsetDateTime = localDateTime.atZone(zoneId).toOffsetDateTime()
    // get the time in epoch milliseconds
    val timeInMillis = odt.toInstant().toEpochMilli()
    // and print it
    println("$odt ==> $timeInMillis")
}

此示例代码生成以下输出(注意datetime表示中的尾随Z,这是+00:00时数的偏移量,UTC时区,我在Kotlin游乐场中编写了这段代码,它似乎有UTC时区;- ):

代码语言:javascript
复制
2020-09-22T20:35Z ==> 1600806900000

请注意,我在java.time上尝试过这一点,而不是ThreeTen ABP,因为现在有Android去加林,所以对于许多(较低的)安卓版本来说,这已经过时了。但是,这并没有什么不同,因为在我第一次尝试的时候,示例代码抛出了完全相同的异常,这意味着这不应归咎于ThreeTen。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64022099

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档