最近,我使用LocalDate.atStartOfDay()和LocalDate.atTime(LocalTime.MIN)回答了一些问题。
我想知道为什么没有LocalDate.atEndOfDay()或类似的,所以我们必须使用LocalDate.atTime(LocalTime.MAX)才能得到那个特定日子的最后一刻(在nanos中,我认为)。
我看了一下LocalDate和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);
}与我的预期相反,此方法使用LocalTime.MIDNIGHT而不是LocalTime.MIN返回一个LocalTime.MIN。
当然,我打开了OpenJDK source of 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);
}虽然我完全理解NOON和MAX的存在,但我并不真正理解为什么会有MIN和MIDNIGHT,因为它们具有相同的价值,显然其中的一个就足够了。
有人能告诉我为什么..。
MIDNIGHT?这仅仅是为了在某些情况下有更好的可读性吗?
但是为什么MIN不是在LocalTime.atStartOfDay()中使用,而是在LocalTime.MIDNIGHT中使用?
发布于 2021-06-16 08:19:42
MIN的存在是为了提供最小值,这与其他java.time.*类是一致的。
MIDNIGHT的存在是为了向开发人员提供语义意义,也是向Javadoc读者表明午夜被认为是一天的开始(而不是结束)的地方。
总之,阅读代码的语义优势超过了额外常量的成本。
(来源:我是java.time.*作者)
https://stackoverflow.com/questions/67998391
复制相似问题