How can I validate a local date time within daylight savings time?

前端 未结 2 1207
鱼传尺愫
鱼传尺愫 2020-12-11 01:34

Mar 12, 2017 02:39:00 \"America/Chicago\" does not exist. When I set the date and time to this value it does not fail. The time gets set to Mar 12, 2017 0

相关标签:
2条回答
  • 2020-12-11 01:40

    Here a validation without throwing exceptions. You only need to ask the zone rules if a LocalDateTime is valid within a given timezone:

    public static boolean isValid(LocalDateTime ldt, ZoneId zoneId) {
        return !zoneId.getRules().getValidOffsets(ldt).isEmpty();
    }
    
    0 讨论(0)
  • 2020-12-11 02:03

    Your sample doesn't throw an exception because ZonedDateTime.of(..) adjusts the date time. The javadoc states

    This creates a zoned date-time matching the input local date-time as closely as possible. Time-zone rules, such as daylight savings, mean that not every local date-time is valid for the specified zone, thus the local date-time may be adjusted.

    You could use ZonedDateTime#ofStrict(LocalDateTime, ZoneOffset, ZoneId) to perform the validation.

    Obtains an instance of ZonedDateTime strictly validating the combination of local date-time, offset and zone ID.

    This creates a zoned date-time ensuring that the offset is valid for the local date-time according to the rules of the specified zone. If the offset is invalid, an exception is thrown.

    You'll first need to construct a LocalDateTime. Then you'll get the ZoneOffset for your ZoneId for that local date time. Then you can provide all three to ofStrict.

    For example,

    ZoneId zoneId = ZoneId.of("America/Chicago");
    LocalDateTime ldt = LocalDateTime.of(2017, 3, 12, 2, 39, 0, 0);
    ZoneOffset zoneOffset = zoneId.getRules().getOffset(ldt);
    ZonedDateTime zdt = ZonedDateTime.ofStrict(ldt, zoneOffset, zoneId);
    

    would throw

    Exception in thread "main" java.time.DateTimeException: LocalDateTime '2017-03-12T02:39' does not exist in zone 'America/Chicago' due to a gap in the local time-line, typically caused by daylight savings
        at java.time.ZonedDateTime.ofStrict(ZonedDateTime.java:484)
    
    0 讨论(0)
提交回复
热议问题