我需要将dateTime String转换为millis,为此我使用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()发布于 2020-09-23 06:46:46
问题是String中缺少的偏移量,您正试图将其解析为OffsetDateTime。一个OffsetDateTime不能在没有ZoneOffset的情况下创建,但是不能从这个String派生出任何ZoneOffset (人们可以猜测它是UTC,但是猜测在这种情况下是不合适的)。
您可以将String解析为LocalDateTime (一天中的日期和时间的表示而没有区域或偏移),然后添加/附加所需的偏移量。您甚至不需要自定义DateTimeFormatter,因为您的String是ISO格式的,可以使用默认的内置格式化程序进行解析:
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时区;- ):
2020-09-22T20:35Z ==> 1600806900000请注意,我在java.time上尝试过这一点,而不是ThreeTen ABP,因为现在有Android去加林,所以对于许多(较低的)安卓版本来说,这已经过时了。但是,这并没有什么不同,因为在我第一次尝试的时候,示例代码抛出了完全相同的异常,这意味着这不应归咎于ThreeTen。
https://stackoverflow.com/questions/64022099
复制相似问题