ThreeTenABP DateTime解析器为yyyy-MM-ddTHH:mm:ss formate提供了例外

问题描述

我需要将dateTime String转换为毫,为此我正在使用ThreeTenABP,但是OffSetDateTime.parse无法解析ex的dateTime String"2020-08-14T20:05:00",并给出以下例外情况。

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中使用的代码

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()

解决方法

问题是您要解析为String的{​​{1}}中缺少偏移量。没有OffsetDateTime的情况下无法创建OffsetDateTime,但是不能从此ZoneOffset派生出ZoneOffset(一个人只能猜测是UTC,但是猜测在这种情况下不适合)。

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

String

此示例代码产生以下输出(注意日期时间表示中的尾随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") } ,这是UTC时区Z小时的偏移量,我在Kotlin Playground中编写了此代码并且似乎有UTC时区;-)):

+00:00

请注意,我使用2020-09-22T20:35Z ==> 1600806900000 而不是使用ThreeTen ABP进行了此操作,由于存在Android API Desugaring,因此它现在已在许多(较低)Android版本中废弃。但是,这没有什么区别,因为您的示例代码在我第一次尝试时就抛出了完全相同的异常,这意味着ThreeTen不应为此负责。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...