问题描述
我需要将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不应为此负责。