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
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
}
}