Reputation: 77
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.
Upvotes: 3
Views: 1297
Reputation: 655
With Java 7
public long countDays(Date dtStart, Date dtEnd) {
long startDay = TimeUnit.DAYS.convert(dtStart.getTime(), TimeUnit.MILLISECONDS)
long endDay = TimeUnit.DAYS.convert(dtEnd.getTime(), TimeUnit.MILLISECONDS)
return endDay - startDay
}
Upvotes: 0
Reputation: 2170
Using Joda's DateTime library (one I would recommmend anyway), an elegant way to do so would be:
private int getNumberOfNights(DateTime start, DateTime end) {
int nightCount = 0;
DateTime tempEnd = new DateTime(end);
while (tempEnd.withTimeAtStartOfDay().isAfter(start)) {
nightCount++;
tempEnd = tempEnd.minusDays(1);
}
return nightCount;
}
... or if you want to avoid a while loop:
private int getNumberOfNights(DateTime start, DateTime end) {
int nightCount = Days.daysBetween(start, end).getDays();
DateTime leftOver = new DateTime(end.minusDays(nightCount));
if (leftOver.withTimeAtStartOfDay().isAfter(start)) {
nightCount++;
}
return nightCount;
}
Upvotes: 0
Reputation: 44061
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++;
}
Upvotes: 2
Reputation: 14418
One option is to use Joda-Time library:
DateTimeZone zone = DateTimeZone.forID("America/New_York");
int days = Days.daysBetween(new DateTime(startDate, zone), new DateTime(endDate, zone)).getDays();
I think this is the easiest way. The drawback is that you need one more library..
Hope this can help!
Upvotes: 2
Reputation: 789
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
Upvotes: 3