deH*_*aar 5 java datetime localtime java-time localdate
我最近使用LocalDate.atStartOfDay()和回答了一些问题LocalDate.atTime(LocalTime.MIN)。
我想知道为什么没有LocalDate.atEndOfDay()或类似的,所以必须使用LocalDate.atTime(LocalTime.MAX)才能获得特定日期的最后时刻(我认为是 nanos)。
我查看了LocalDateand的来源并LocalTime对此感到有些困惑:
/**
* 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);
}
Run Code Online (Sandbox Code Playgroud)
与我的预期相反,此方法返回LocalDateTimeusingLocalTime.MIDNIGHT而不是LocalTime.MIN。
当然,我打开了OpenJDK的源码,LocalTime肯定是自己查到了区别,结果发现除了常量的名字没有区别:
/**
* 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);
}
Run Code Online (Sandbox Code Playgroud)
虽然我完全理解NOONand的存在MAX,但我真的不明白为什么存在MIN和MIDNIGHT何时显然其中一个就足够了,因为它们具有完全相同的价值。
谁能告诉我原因...
MIDNIGHT用于一天的开始?只是为了在某些情况下更具可读性吗?
但是为什么不MIN使用 in LocalTime.atStartOfDay()butLocalTime.MIDNIGHT呢?
MIN 存在提供最小值,这与其他 java.time.* 类一致。
MIDNIGHT 存在是为了向开发人员提供语义含义,并作为向 Javadoc 读者表明午夜被认为是一天的开始(而不是结束)的地方。
总结,代码阅读中的语义优势超过了额外常量的成本。
(来源:我是 java.time.* 的主要作者)