Java 8偏移日期解析 [英] Java 8 Offset Date Parsing
问题描述
我需要将以下格式的字符串 2015-01-15-05:00
解析为UTC中的LocalDate(或其他)。
问题是以下代码:
I need to parse a String in the following format 2015-01-15-05:00
to LocalDate(or smth else) in UTC.
The problem is that the following code:
System.out.println(LocalDate.parse("2015-01-15-05:00", DateTimeFormatter.ISO_OFFSET_DATE));
输出 2015-01-15
忽略偏移。所需的输出是 2015-01-16
outputs 2015-01-15
ignoring the offset. The desired output is 2015-01-16
提前致谢!
推荐答案
最简单的答案是使用 OffsetDateTime
来表示数据,但您需要默认时间:
The simplest answer is to use OffsetDateTime
to represent the data, but you need to default the time:
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_OFFSET_DATE)
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.toFormatter();
OffsetDateTime dt = OffsetDateTime.parse("2015-01-15-05:00", fmt);
LocalDate date = dt.withOffsetSameInstant(ZoneOffset.UTC).toLocalDate();
ZonedDateTime
在处理时间时非常有用 - 区域,但是当你只处理偏移时, OffsetDateTime
更简单。
ZonedDateTime
is useful if dealing with time-zones, but when you are only dealing with offsets, OffsetDateTime
is simpler.
通常,应用程序代码不应该保存 TemporalAccessor
类型的变量。如果你看到这一点,通常有更好的方法。
In general, application code should not hold variables of type TemporalAccessor
. If you see that, there is generally a better way.
这篇关于Java 8偏移日期解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!