オプション付きのLocalDateTimeにISO_DATE_TIME.format()オフセット

B_Osipiuk:

私はのLocalDateTimeにISO日時をひそかしようとしています:

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を取得できません:15:{}、ISOは2011-12-03T10に解決タイプの30 java.time.format.Parsed

私はこの例外を持っているなぜ私は質問がある、知っているのLocalDateTimeへのオフセットを含む両方の日付を変換する方法は?私はいくつかの文字列解析を避けたい(文字列は「+」が含まれている場合、チェックを/「 - 」)。

NorthernSky:

あなたは、オプションのオフセット要素とパーサを構築し、オフセットが存在したかどうかを確認するために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);

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=316367&siteId=1