在java.util。日历中,一月被定义为第0个月,而不是第1个月。这有什么具体原因吗?
我看到很多人对此感到困惑……
在java.util。日历中,一月被定义为第0个月,而不是第1个月。这有什么具体原因吗?
我看到很多人对此感到困惑……
当前回答
我想说是懒惰。数组从0开始(每个人都知道);一年中的月份是一个数组,这让我相信Sun的一些工程师只是懒得在Java代码中加入这个小细节。
其他回答
除了DannySmurf关于懒惰的回答之外,我还要补充一句,这是为了鼓励您使用常量,例如Calendar.JANUARY。
因为程序员痴迷于基于0的索引。好吧,实际情况要比这复杂一些:当您使用基于0的索引来处理底层逻辑时,它更有意义。但总的来说,我还是会坚持我的第一句话。
就我个人而言,我认为Java日历API的奇特之处表明,我需要摆脱以格里高利为中心的思维方式,并尝试在这方面更加不可知论地编程。具体来说,我再次学会了避免对月份之类的常量进行硬编码。
下面哪个选项更可能是正确的?
if (date.getMonth() == 3) out.print("March");
if (date.getMonth() == Calendar.MARCH) out.print("March");
这说明了Joda Time让我有点恼火的一件事——它可能会鼓励程序员从硬编码常数的角度思考问题。(不过只有一点点。Joda并不是在强迫程序员糟糕地编程。)
真正的原因
You would think that when we deprecated most of Date and added the new Calendar class, we would have fixed Date's biggest annoyance: the fact that January is month 0. We certainly should have, but unfortunately we didn't. We were afraid that programmers would be confused if Date used zero-based months and Calendar used one-based months. And a few programmers probably would have been. But in hindsight, the fact that Calendar is still zero-based has caused an enormous amount of confusion, and it was probably the biggest single mistake in the Java international API's.
引用自Laura Werner的Java国际日历,链接在底部。
更好的选择:java.time
这可能只是重复其他人所说的,抛弃旧的和设计糟糕的Calendar类,使用java。时间,现代Java日期和时间API。从1月的1到12月的12,月份的编号始终是合理的。
如果您从尚未升级到java的遗留API中获取Calendar。时,要做的第一件事是转换为现代的ZonedDateTime。根据你的需要,你可以从那里做进一步的转换。在大多数情况下,您获得的Calendar对象实际上总是GregorianCalendar子类的一个实例(因为Calendar类本身是抽象的)。demonstreate:
Calendar oldfashionedCalendarObject = Calendar.getInstance();
ZonedDateTime zdt
= ((GregorianCalendar) oldfashionedCalendarObject).toZonedDateTime();
System.out.println(zdt);
System.out.format("Month is %d or %s%n", zdt.getMonthValue(), zdt.getMonth());
当我刚刚在我的时区运行时输出:
2021 - 03 - 17 - t23:18:47.761 + 01:00[欧洲/哥本哈根] 月是3号或MARCH
链接
Laura Werner编写的Java国际日历 Oracle教程:Date Time解释如何使用java.time。
There has been a lot of answers to this, but I will give my view on the subject anyway. The reason behind this odd behavior, as stated previously, comes from the POSIX C time.h where the months were stored in an int with the range 0-11. To explain why, look at it like this; years and days are considered numbers in spoken language, but months have their own names. So because January is the first month it will be stored as offset 0, the first array element. monthname[JANUARY] would be "January". The first month in the year is the first month array element.
另一方面,由于日期数字没有名称,将它们存储在0-30的int型中会令人困惑,添加大量的day+1指令用于输出,当然,也容易出现很多错误。
也就是说,这种不一致是令人困惑的,特别是在javascript(它也继承了这个“特性”)中,这种脚本语言应该从语言中抽象出来。
因为月份有名称,而月份中的日期没有。