Search code examples
javatimeintervalslocaltime

Generate specific intervals between two time/date in Java


I want to generate intervals between two given date/time.
For instance, say for 24 hour format (HH:MM), I have these two endpoints, 00:00 and 11:51, and suppose I want to partition it in 24 pieces. So my calculation is like this:

(hour * 3600 + min * 60) / 24

If I use calendar.add(Calendar.SECOND, (hour * 3600 + min * 60) / 24), I am getting wrong dates/time. My calculation is double and I think calendar.add() does not support double. Like it is taking 28.883 as 29.

In essence I want something like this:

now : 15:57
today start : 00:00 (24hh)
output : 00:00, 00:47.85, …, 15:57


Solution

  • The actual problem with your code is that you are performing integer division. I assume both hour and min are defined as integer types. The formula (hour * 3600 + min * 60) / 24 always yields an integer type. If you change the code to (hour * 3600 + min * 60) / 24d the expression yields a floating point value at least.

    The next problem is indeed that Calendar.add(int field, int amount) accepts only an integer as second argument. Of course, if you are passing Calendar.SECOND as first argument, then your precision is not higher than seconds. You can use Calendar.MILLISECOND to get a higher precision.

    However, I suggest using the new Java Date and Time API, instead of the troublesome old API:

    LocalTime startTime = LocalTime.of(0, 0);
    LocalTime endTime = LocalTime.of(11, 51);
    long span = Duration.between(startTime, endTime).toNanos();
    
    final int n = 23; // Number of pieces
    LongStream.rangeClosed(0, n)
        .map(i -> i * span / n)
        .mapToObj(i -> startTime.plusNanos(i))
        .forEach(System.out::println);