Java 8 Offset Date Parsing

独自空忆成欢 提交于 2019-12-09 02:54:22

问题


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

outputs 2015-01-15 ignoring the offset. The desired output is 2015-01-16

Thanks in advance!


回答1:


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 is useful if dealing with time-zones, but when you are only dealing with offsets, OffsetDateTime is simpler.

In general, application code should not hold variables of type TemporalAccessor. If you see that, there is generally a better way.




回答2:


Seems like I've found a solution. Here it is:

TemporalAccessor temporalAccessor = DateTimeFormatter.ISO_OFFSET_DATE.parse("2015-01-15-05:00");
ZonedDateTime zonedDateTime = ZonedDateTime.of(LocalDate.from(temporalAccessor), LocalTime.MAX, ZoneId.from(temporalAccessor));
System.out.println(zonedDateTime.withZoneSameInstant(ZoneOffset.UTC).toLocalDate());


来源:https://stackoverflow.com/questions/34810324/java-8-offset-date-parsing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!