Question

I am getting incorrect results because of the daylight savings for that day.

I used,

Calendar todays = Calendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles"));
todays.set(Calendar.HOUR_OF_DAY, 24);
todays.set(Calendar.MINUTE, 0);
todays.set(Calendar.SECOND, 0);
todays.set(Calendar.MILLISECOND, 0);

As mentioned in Joda-Time doc,

Consider adding 1 day at the daylight savings boundary. If you use a period to do the addition then either 23 or 25 hours will be added as appropriate. If you had created a duration equal to 24 hours, then you would end up with the wrong result.

I didn't found any example of how to implement such a period using Joda-Time.

So, I want to get the number of hours contained in each day dynamically rather hard coding it with 24 hours as mentioned.

Était-ce utile?

La solution

The simplest approach is probably to use something like:

public int getHoursInDay(LocalDate date, DateTimeZone zone) {
    DateTime start = date.toDateTimeAtStartOfDay(zone);
    DateTime end = date.plusDays(1).toDateTimeAtStartOfDay(zone);
    return new Duration(start, end).getStandardHours();
}

EDIT: If you're using a version of Joda Time which doesn't support Duration.getStandardHours() you could use:

public int getHoursInDay(LocalDate date, DateTimeZone zone) {
    DateTime start = date.toDateTimeAtStartOfDay(zone);
    DateTime end = date.plusDays(1).toDateTimeAtStartOfDay(zone);
    long millis = new Duration(start, end).getMillis();
    return (int) (millis / DateTimeConstants.MILLIS_PER_HOUR);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top