Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of days between two dates in Joda-Time

How do I find the difference in Days between two Joda-Time DateTime instances? With ‘difference in days’ I mean if start is on Monday and end is on Tuesday I expect a return value of 1 regardless of the hour/minute/seconds of the start and end dates.

Days.daysBetween(start, end).getDays() gives me 0 if start is in the evening and end in the morning.

I'm also having the same issue with other date fields so I was hoping there would be a generic way to 'ignore' the fields of lesser significance.

In other words, the months between Feb and 4 March would also be 1, as would the hours between 14:45 and 15:12 be. However the hour difference between 14:01 and 14:55 would be 0.

like image 581
pvgoddijn Avatar asked Sep 27 '10 10:09

pvgoddijn


People also ask

Is Joda time deprecated?

So the short answer to your question is: YES (deprecated).

What is the replacement of Joda time?

Correct Option: D. In java 8,we are asked to migrate to java. time (JSR-310) which is a core part of the JDK which replaces joda library project.

Does Joda DateTime have TimeZone?

Adjusting Time ZoneUse the DateTimeZone class in Joda-Time to adjust to a desired time zone. Joda-Time uses immutable objects. So rather than change the time zone ("mutate"), we instantiate a new DateTime object based on the old but with the desired difference (some other time zone).

What is Joda time package?

time Description. Provides support for dates, times, time zones, durations, intervals, and partials. This package aims to fully replace the Java Date , Calendar , and TimeZone classes.


2 Answers

Annoyingly, the withTimeAtStartOfDay answer is wrong, but only occasionally. You want:

Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays() 

It turns out that "midnight/start of day" sometimes means 1am (daylight savings happen this way in some places), which Days.daysBetween doesn't handle properly.

// 5am on the 20th to 1pm on the 21st, October 2013, Brazil DateTimeZone BRAZIL = DateTimeZone.forID("America/Sao_Paulo"); DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, BRAZIL); DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, BRAZIL); System.out.println(daysBetween(start.withTimeAtStartOfDay(),                                end.withTimeAtStartOfDay()).getDays()); // prints 0 System.out.println(daysBetween(start.toLocalDate(),                                end.toLocalDate()).getDays()); // prints 1 

Going via a LocalDate sidesteps the whole issue.

like image 159
Alice Purcell Avatar answered Sep 29 '22 10:09

Alice Purcell


Days Class

Using the Days class with the withTimeAtStartOfDay method should work:

Days.daysBetween(start.withTimeAtStartOfDay() , end.withTimeAtStartOfDay() ).getDays()  
like image 44
Michael Borgwardt Avatar answered Sep 29 '22 10:09

Michael Borgwardt