簡體   English   中英

ISO_DATE_TIME.format()到具有可選偏移量的LocalDateTime

[英]ISO_DATE_TIME.format() to LocalDateTime with optional offset

我試圖將ISO日期時間轉換為LocalDateTime:

String timezone = "Pacific/Apia";
String isoDateTime = "2011-12-03T10:15:30+03:00";
var zoned = ZonedDateTime.from(ISO_DATE_TIME_FORMATTER.parse(isoDateTime));
return zoned.withZoneSameInstant(ZoneId.of(timeZone)).toLocalDateTime();

此代碼有效 - 它將其轉換為包括偏移量的localdate。 但問題是當我沒有抵消時通過日期: 2011-12-03T10:15:30 -

java.time.DateTimeException:無法從TemporalAccessor獲取ZonedDateTime:{},ISO已解析為類型為java.time.format.Parsed的2011-12-03T10:15:30

我知道為什么我有這個例外,問題是如何將包括偏移在內的兩個日期轉換為LocalDateTime? 我想避免一些字符串解析(檢查字符串是否包含'+'/' - ')。

您可以使用可選的offset元素構建解析器,並使用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);

您可以在catch子句中處理parse異常並嘗試使用其他解析器。 例如這樣:

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM