How to show the difference in time after the daylight saving started in Java?

前端 未结 2 930
旧时难觅i
旧时难觅i 2020-12-20 07:22

I wanted to check the difference in time before and after the daylight saving time started. I am using a JVM where timezone has some issue with DST WRT Brazilian time. I cou

相关标签:
2条回答
  • 2020-12-20 07:25

    I'll add a very brief answer. It shows that 1 day is not equal to 24 hours, i.e. DST changed. I also stepped over to Java 8 because I'm more familiar with it.

    ZoneId timezone = ZoneId.of("Brazil/East");
    
    ZonedDateTime t = ZonedDateTime.of(2018, 10, 20, 7, 52, 16, 0, timezone);
    
    System.out.println(t);
    System.out.println(t.plus(1, ChronoUnit.DAYS));
    System.out.println(t.plus(24, ChronoUnit.HOURS));
    

    Output:

    2018-10-20T07:52:16-03:00[Brazil/East]
    2018-10-21T07:52:16-02:00[Brazil/East]
    2018-10-21T08:52:16-02:00[Brazil/East]

    0 讨论(0)
  • 2020-12-20 07:26

    The solution is to fix the JVM with the faulty (outdated) time zone data. It’s pretty straightforward to do using the Time Zone Updater Tool from Oracle. See the link at the bottom (for OpenJDK see the next link).

    If you want to know when your JVM “thinks” that summer time (DST) began, you may use the following code:

        ZoneId zone = ZoneId.of("America/Sao_Paulo");
        ZoneRules rules = zone.getRules();
        ZoneOffsetTransition dstStarted = rules.previousTransition(Instant.now());
        System.out.println(dstStarted);
    

    Apparently my Java 11 has the fresh time zone data where summer began on November 4. I got this output:

    Transition[Gap at 2018-11-04T00:00-03:00 to -02:00]

    “Gap” means that the clock was turned forward as when summer time begins. The transitions were the clock is turned backward are printed as “Overlap”.

    If you want, you can also query the ZoneOffsetTransition about the local date and time before and after the transition, the instant of the transition, the UTC offset applied before and after the transition, the signed length of the transition (here 1 hour) and other information.

    I am recommending java.time, the modern Java date and time API. The date-time classes that you were using — TimeZone, Calendar, DateFormat, SimpleDateFormat and Date — are all poorly designed and long outdated.

    Links

    • Timezone Updater Tool (for Oracle JDK)
    • How do I update the timezone information for the OpenJDK? (credits to Matt Johnson, who provided this link in a comment)
    • Oracle tutorial: Date Time explaining how to use java.time.
    0 讨论(0)
提交回复
热议问题