java - 为什么 YearMonth 是 Temporal 而 MonthDay 不是 Temporal?

标签 java java-time

为什么 YearMonth 类是 Temporal(接口(interface))而 MonthDay 不是 Temporal?

这看起来很奇怪,因为这两个类的含义几乎相同。

我可能会建议永远不要在使用 Temporal 接口(interface)的任何地方使用 MonthDay,但也许有更好的理由。

最佳答案

这是一道阅读MonthDay文档的题,感谢davidxxx等人找到正确的引用:

This class implements TemporalAccessor rather than Temporal. 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 fields MONTH_OF_YEAR and DAY_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/

相关文章:

java - 如何将一个持续时间除以另一个持续时间?

java - 无法在java中将字符串转换为MM/dd/yyyy格式

java - 如何在 JUnit 测试中运行 Spring Shell 脚本

java - 为什么我收到“属性值必须是常量”错误?

java - Checkstyle 警告 Eclipse "Javadoc tag should be preceded with an empty line"即使有一个

Java:添加全局鼠标监听器

java - 循环遍历 JSON 键以获取值

java - Java 8 中的时间戳用户输入

java - 从 java.time.MonthDay 到 java.sql.* 的映射

java - android onKeyDown onKeyUp 测量时间