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

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

Like this:

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

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

The calculation should be based only on the dates and month of the year (not including time). Please help me. Thanks in advance...

+3
source share
3 answers

In Java, I think you will lose time and calculate the difference per day

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 ... , " ", . , . joda time library.

+2

FYI, Groovy :

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

1,

+2

, 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
0

Source: https://habr.com/ru/post/1796217/


All Articles