为什么 YearMonth
类是 Temporal(接口(interface))而 MonthDay
不是 Temporal?
这看起来很奇怪,因为这两个类的含义几乎相同。
我可能会建议永远不要在使用 Temporal 接口(interface)的任何地方使用 MonthDay,但也许有更好的理由。
最佳答案
这是一道阅读MonthDay
文档的题,感谢davidxxx等人找到正确的引用:
This class implements
TemporalAccessor
rather thanTemporal
. This is because it is not possible to define whether February 29th is valid or not without external information, preventing the implementation of plus/minus. Related to this,MonthDay
only provides access to query and set the fieldsMONTH_OF_YEAR
andDAY_OF_MONTH
.
您可以结合 Temporal
文档中的此片段阅读此内容:
This is the base interface type for date, time and offset objects that are complete enough to be manipulated using plus and minus.
他们不想为 MonthDay
定义加号和减号。因为例如不清楚 2 月 28 日加 1 天是什么。有些年份是 2 月 29 日,有些年份是 3 月 1 日。
相比之下,将月份或年份添加到 YearMonth
总是会给出定义明确且不足为奇的结果。
链接
关于java - 为什么 YearMonth 是 Temporal 而 MonthDay 不是 Temporal?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56466048/