2 回答

TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超3個(gè)贊
您可以構(gòu)建一個(gè)帶有可選偏移量元素的解析器,并使用 TemporalAccessor.isSupported 檢查偏移量是否存在。
DateTimeFormatter parser = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
.optionalStart()
.appendOffsetId()
.optionalEnd()
.toFormatter();
TemporalAccessor accessor = parser.parse(isoDateTime);
if (accessor.isSupported(ChronoField.OFFSET_SECONDS)) {
var zoned = ZonedDateTime.from(accessor);
return zoned.withZoneSameInstant(ZoneId.of(timezone)).toLocalDateTime();
}
return LocalDateTime.from(accessor);

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超10個(gè)贊
您可以在子句中處理解析異常catch并嘗試不同的解析器。例如像這樣:
String timezone = "Pacific/Apia"
String isoDateTime = "2011-12-03T10:15:30+03:00";
try{
var zoned = ZonedDateTime.from(ISO_DATE_TIME_FORMATTER.parse(isoDateTime));
return zoned.withZoneSameInstant(ZoneId.of(timeZone)).toLocalDateTime();
} catch (DateTimeException e) {
//no time zone information -> parse as LocalDate
return LocalDateTime.parse(isoDateTime);
}
添加回答
舉報(bào)