maaz
maaz

Reputation: 3664

How to get Exact day difference between two dates in java or groovy?

I am calculating the difference between two sql dates, TripStartDate and TripEndDate.
If TripStartDate= 2011-03-04 09:35:00 and TripEndDate = 2011-03-04 10:35:00 then I should get the number of day is 1 (because trip happened on that day).

Like this:

If TripStartDate = 2011-03-04 09:35:00 and TripEndDate = 2011-03-05 09:35:00 then method should return 2 days (because trip happened on both days).

If TripStartDate = 2011-03-04 09:35:00 and TripEndDate = 2011-04-04 09:35:00 then method should return 32 days. (because 28 days in march and 4 days in April).

Calculation should be based on only dates and month of year (not taking time in consideration). Please help me . Thanks in advance...

Upvotes: 3

Views: 4907

Answers (3)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79848

Here's the usual way to do this, in Java 8.

LocalDate start = LocalDate.of(2011, 3, 4);  // Or whatever - this is Y, M, D
LocalDate end = LocalDate.of(2011, 4, 4);
return ChronoUnit.DAYS.between(start, end) + 1; 
                                         // The +1 is for the inclusive reckoning

Upvotes: 0

tim_yates
tim_yates

Reputation: 171114

FYI, in Groovy this would be something along the lines of:

fourthMarch = Date.parse( 'yyyy-MM-dd', '2011-03-04' )
fifthMarch  = Date.parse( 'yyyy-MM-dd', '2011-03-05' )
fourthApril = Date.parse( 'yyyy-MM-dd', '2011-04-04' )

assert 2  == fifthMarch  - fourthMarch + 1
assert 32 == fourthApril - fourthMarch + 1

We need to add 1 as the dates are inclusive

Upvotes: 2

m0s
m0s

Reputation: 4280

In Java I guess you would drop the time and calculate the day difference

Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.set(2011, 03, 04);
cal2.set(2011, 04, 04);
long milis1 = cal1.getTimeInMillis();
long milis2 = cal2.getTimeInMillis();
long diff = milis2 - milis1;
long days = diff / (24 * 60 * 60 * 1000);

EDIT Quite surprisingly for me, that ^ code really doesn't work always... apparently there are some 'leap seconds' that mess up the maths. There are quite enough links already proposed to you in comments. I would go with joda time library.

Upvotes: 2

Related Questions