I am trying to write a java block to find the number of mid-nights in a particular date range.
For example:
begin date: 05/01/2014 00:00:00 end date : 05/03/2014 00:00:00
this range has 3 mid-nights in it.
or
begin date : 05/01/2014 00:00:00 end date : 05/02/2014 23:59:59
this has only one.
It basically has to tell me how many times the time "00:00:00" occurrs in the date range. Please help me out. I tried many approaches but none work correct.
I would just count the days (the actual dates), and add one if the earliest date has a time of 00:00:00.
begin date: 05/01/2014 00:00:00 end date : 05/03/2014 00:00:00
or
begin date : 05/01/2014 00:00:00 end date : 05/02/2014 23:59:59
Also,
begin date : 5/01/2014 23:59:59 end date : 5/02/2014 00:00:01
The answer using Joda-Time is not correct. As @khriskooper has noted the count of midnights between
2014-05-01 00:00:00 and 2014-05-02 23:59:59
is not one but two midnights!
So here the correction using Joda-Time (not tested), but it could also be any other library which supports day-range calculations (not true for old Java-pre8). I leave out the timezone detail because I do not consider it as really relevant for the question. If OP wants he can replace LocalDateTime by DateTime and apply a timezone.
LocalDateTime ldt1 = new LocalDateTime(2014, 5, 1, 0, 0, 0);
LocalDateTime ldt2 = new LocalDateTime(2014, 5, 2, 23, 59, 59);
int days = Days.daysBetween(ldt1.toLocalDate(), ldt2.toLocalDate()).getDays();
if (ldt1.toLocalTime().equals(new LocalTime(0, 0))) {
days++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With