2

我需要将 dateTime 转换为String毫秒,并且为此使用 ThreeTenABP,但是OffSetDateTime.parse无法解析String用于 ex 的 dateTime。"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()
4

1 回答 1

3

问题是String您尝试解析为OffsetDateTime. OffsetDateTime没有 a 就无法创建,但ZoneOffset不能ZoneOffset从中派生String(人们可能只是猜测它是 UTC,但在这种情况下猜测不合适)。

您可以将其解析String为 a 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")
}

这个示例代码产生以下输出(注意Z日期时间表示中的尾随,这是+00:00小时的偏移量,UTC 时区,我在 Kotlin Playground 中编写了这段代码,它似乎有 UTC 时区 ;-)):

2020-09-22T20:35Z ==> 1600806900000

请注意,我尝试使用而不是使用 ThreeTen ABP 进行此操作,因为有Android API Desugaringjava.time,它现在已过时用于许多(较低)Android 版本。但是,这应该没有什么不同,因为当我第一次尝试时,您的示例代码抛出了完全相同的异常,这意味着 ThreeTen 不应该为此负责。

于 2020-09-23T06:46:46.173 回答