How to get correct number of hours between Joda dates?

后端 未结 3 420
时光说笑
时光说笑 2021-01-22 02:59

I want to get all the Daylight Saving Time (DST) hours between two dates.

This is my example code:

public static void main(String[] args) {

    Date sta         


        
3条回答
  •  囚心锁ツ
    2021-01-22 03:28

    Welcome to the chaos that is date / time handling. Your problem is time zones. Specifically, whatever time zone you're in observes daylight saving time, and the switch (spring forward) occurs during your interval, which shortens it by an hour. See this code.

    public class DateTimeTest {
        public static void main(String[] args) {
        DateTime startDateTime = new DateTime()
            .withYear(2014)
            .withMonthOfYear(3)
            .withDayOfMonth(1)
            .withHourOfDay(0)
            .withMinuteOfHour(0)
            .withSecondOfMinute(0)
            .withMillisOfSecond(0)
            .withZone(DateTimeZone.forID("US/Eastern"));
    
        DateTime endDateTime = new DateTime()
            .withYear(2014)
            .withMonthOfYear(3)
            .withDayOfMonth(31)
            .withHourOfDay(0)
            .withMinuteOfHour(0)
            .withSecondOfMinute(0)
            .withMillisOfSecond(0)
            .withZone(DateTimeZone.forID("US/Eastern"))
            .plusDays(1);
    
        System.out.println("Expected 744, got: " 
            + Hours.hoursBetween(startDateTime, endDateTime).getHours());  // 743
    
        DateTime startUtc = startDateTime.withZoneRetainFields(DateTimeZone.UTC);
        DateTime endUtc = endDateTime.withZoneRetainFields(DateTimeZone.UTC);
    
        System.out.println("Expected 744, got: " 
            + Hours.hoursBetween(startUtc, endUtc).getHours());  // 744
        }
    }
    

提交回复
热议问题