gpt4 book ai didi

java - ISO_DATE_TIME.format() 到具有可选偏移量的 LocalDateTime

转载 作者:行者123 更新时间:2023-11-29 04:07:31 25 4
gpt4 key购买 nike

我正在尝试将 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();

此代码有效 - 它将其转换为包含偏移量的本地日期。但问题是当我在没有偏移的情况下传递日期时:2011-12-03T10:15:30 -

java.time.DateTimeException: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 2011-12-03T10:15:30 of type java.time.format.Parsed

我知道为什么会出现此异常,问题是如何将两个日期(包括偏移量)转换为 LocalDateTime?。我想避免一些字符串解析(检查字符串是否包含“+”/“-”)。

最佳答案

您可以构建一个带有可选偏移量元素的解析器,并使用 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);

关于java - ISO_DATE_TIME.format() 到具有可选偏移量的 LocalDateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57559087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com