Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (4k points)

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.

1 Answer

0 votes
by (46k points)

sadly, the withTimeAtStartOfDay answer is not correct, but only sometimes. You want:

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

It directs out that "midnight/start of day" sometimes involves 1 am (daylight savings appear this way in some areas), which Days.daysBetween doesn't hand accurately.

// 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);



// prints 0



// prints 1

Going through a LocalDate sidesteps the entire problem.

Related questions

0 votes
1 answer
asked Jul 31, 2019 in Java by noah kapoor (5.3k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 16, 2019 in SQL by Tech4ever (20.3k points)

Browse Categories