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
使用LocalDate
代替LocalDateTime
,例如:
val begin = (LocalDate.parse("2019-11-04", dateFormatter).atOffset(ZoneOffset.UTC)
.toInstant()).atZone(ZoneId.of(timeZoneIdentifier))
但是此调用需要至少api26。有关较旧的API,请参见here
由于2019-11-04
是ISO 8601格式,LocalDate
和其他java.time类将ISO 8601格式解析为默认格式,因此您不需要任何显式格式化程序。就是这个:
val begin = LocalDate.parse("2019-11-04")
.atStartOfDay(ZoneOffset.UTC)
.withZoneSameInstant(ZoneId.of(timeZoneIdentifier))
假设timeZoneIdentifier
为Europe/Bucharest
,结果为ZonedDateTime
的2019-11-04T02:00+02:00[Europe/Bucharest]
。
您无法将字符串解析为LocalDateTIme
。这不仅需要日期,而且还需要一天中的时间,并且您知道,您的字符串仅包含前者。