Java 8 Offset Date Parsing

前端 未结 2 1102
盖世英雄少女心
盖世英雄少女心 2021-01-11 23:01

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:

Sys         


        
相关标签:
2条回答
  • 2021-01-11 23:18

    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());
    
    0 讨论(0)
  • 2021-01-11 23:24

    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.

    0 讨论(0)
提交回复
热议问题