org.threeten.bp.format.DateTimeParseException

问题描述 投票:0回答:2
val dateFormatter= DateTimeFormatterBuilder()
        .appendPattern("yyyy-MM-dd")
        .toFormatter()  

val begin = (LocalDateTime.parse("2019-11-04", dateFormatter).atOffset(ZoneOffset.UTC)
                    .toInstant()).atZone(ZoneId.of(timeZoneIdentifier))

当我尝试这样解析日期时,出现以下错误:

文本'2019-11-04'无法解析:无法从TemporalAccessor获取LocalDateTime:DateTimeBuilder [,ISO,null,2019-11-04,null],键入org.threeten.bp.format .DateTimeBuilder

android date kotlin date-parsing threetenabp
2个回答
0
投票

使用LocalDate代替LocalDateTime,例如:

val begin = (LocalDate.parse("2019-11-04", dateFormatter).atOffset(ZoneOffset.UTC)
                .toInstant()).atZone(ZoneId.of(timeZoneIdentifier))

但是此调用需要至少api26。有关较旧的API,请参见here


0
投票

由于2019-11-04是ISO 8601格式,LocalDate和其他java.time类将ISO 8601格式解析为默认格式,因此您不需要任何显式格式化程序。就是这个:

    val begin = LocalDate.parse("2019-11-04")
            .atStartOfDay(ZoneOffset.UTC)
            .withZoneSameInstant(ZoneId.of(timeZoneIdentifier))

假设timeZoneIdentifierEurope/Bucharest,结果为ZonedDateTime2019-11-04T02:00+02:00[Europe/Bucharest]

您无法将字符串解析为LocalDateTIme。这不仅需要日期,而且还需要一天中的时间,并且您知道,您的字符串仅包含前者。

链接: Wikipedia article: ISO 8601

© www.soinside.com 2019 - 2024. All rights reserved.