Java code to calculate number of mid nights (00:00:00) in a date range

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.


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++;
}

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

  • 03 - 01 = 2 days.
  • Since the begin date has a time of 00:00:00, then add one:
  • 2 + 1 = 3 midnights.
  • or

    begin date : 05/01/2014 00:00:00 end date : 05/02/2014 23:59:59

  • 02 - 01 = 1 day.
  • Since the begin date has a time of 00:00:00, then add one:
  • 1 + 1 = 2 midnights.
  • Also,

    begin date : 5/01/2014 23:59:59 end date : 5/02/2014 00:00:01

  • 02 - 01 = 1 day.
  • Since the begin date doesn't have a time of 00:00:00, then don't add one:
  • 1 midnight.

  • 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!

    链接地址: http://www.djcxy.com/p/36674.html

    上一篇: git可以被告知在〜/ .gitconfig中使用空格吗?

    下一篇: Java代码来计算日期范围中的夜晚(00:00:00)的数量