Search code examples
javadatetimejava-timelocaldatelocaltime

LocalTime.MIDNIGHT vs. LocalTime.MIN - is there any difference?


I recently answered some questions using LocalDate.atStartOfDay() and LocalDate.atTime(LocalTime.MIN).
I was wondering why there is no LocalDate.atEndOfDay() or similar, so one has to use LocalDate.atTime(LocalTime.MAX) in order to get the very last moment (in nanos, I think) of that specific day.

I had a look at the source of LocalDate and LocalTime and got slightly confused by this:

/**
 * Combines this date with the time of midnight to create a {@code LocalDateTime}
 * at the start of this date.
 * <p>
 * This returns a {@code LocalDateTime} formed from this date at the time of
 * midnight, 00:00, at the start of this date.
 *
 * @return the local date-time of midnight at the start of this date, not null
 */
public LocalDateTime atStartOfDay() {
    return LocalDateTime.of(this, LocalTime.MIDNIGHT);
}

Contrary to my expectation, this method returns a LocalDateTime using LocalTime.MIDNIGHT instead of LocalTime.MIN.
Of course, I opened the OpenJDK source of LocalTime and was sure to find out the difference myself, but I found out there is no difference apart from the name of the constant:

/**
 * Constants for the local time of each hour.
 */
private static final LocalTime[] HOURS = new LocalTime[24];
static {
    for (int i = 0; i < HOURS.length; i++) {
        HOURS[i] = new LocalTime(i, 0, 0, 0);
    }
    MIDNIGHT = HOURS[0];   // <--- == MIN
    NOON = HOURS[12];
    MIN = HOURS[0];        // <--- == MIDNIGHT
    MAX = new LocalTime(23, 59, 59, 999_999_999);
}

While I totally understand the presence of NOON and MAX, I don't really get why there are MIN and MIDNIGHT when obviously one of them would be enough since they have the very same value.

Can anyone tell me the reason why...

  • ... there are two constants having the very same value and
  • ... why the code uses MIDNIGHT for the start of a day?

Is it just for having something more readable in some situations?
But why isn't MIN used in LocalTime.atStartOfDay() but rather LocalTime.MIDNIGHT?


Solution

  • MIN exists to provide the minimum value, which is consistent with other java.time.* classes.

    MIDNIGHT exists to provide semantic meaning to developers, and as a place to indicate to Javadoc readers that midnight is considered to be at the start of the day (not the end).

    Summary, the semantic benefits in code reading outweigh the cost of the extra constant.

    (Source: I'm the main java.time.* author)