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
?
MIDNIGHT
the end of a day and somewhere else people consider it the start of a day while you regard it as both. Ok, that will count as natural depending on the location, culture or maybe just mood. From a mathematical point of view,MIN
andMAX
would suffice, I think (yes,NOON
would be allowed to stay). And maths is the same all over the world ;-) – FictionSTART_OF_DAY
. To me this is preciser asMIDNIGHT
(not being a native English speaker). And using half-open intervals I would object to anEND_OF_DAY
constant. The day doesn’t end until the next day begins, and the end of the day should be represented as the beginning of the next day, exclusive. – Anatolian