在java.util。日历中,一月被定义为第0个月,而不是第1个月。这有什么具体原因吗?
我看到很多人对此感到困惑……
在java.util。日历中,一月被定义为第0个月,而不是第1个月。这有什么具体原因吗?
我看到很多人对此感到困惑……
当前回答
基于C的语言在某种程度上复制了C。tm结构(在time.h中定义)有一个整数字段tm_mon,(注释的)范围为0-11。
基于C的语言从索引0开始数组。因此,这对于以tm_mon作为索引输出月份名称数组中的字符串非常方便。
其他回答
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(它也继承了这个“特性”)中,这种脚本语言应该从语言中抽象出来。
因为月份有名称,而月份中的日期没有。
它本身并没有定义为0,而是定义为Calendar.January。这是使用整数作为常量而不是枚举的问题。日历。1月== 0。
因为所有东西都是从0开始的。这是Java编程的一个基本事实。如果有一件事偏离了这一点,那么就会导致一系列的混乱。让我们不要争论它们的构成和代码。
设置月份为“日历”。MARCH,或者比较,看看它是否== Calendar。比如六月。
Date和Calendar类可以追溯到Java的早期,当时人们还在摸索,它们被广泛认为设计得不是很好。
如果今天用相同的设计创建Calendar,而不是int类型的Calendar。JUNE等等,他们会用枚举。
java.time.Month
Java为您提供了另一种使用基于1的索引的方法。使用java.time.Month enum。为12个月中的每个月预定义一个对象。他们在1月到12月之间分别有1-12号;调用getValue获取该号码。
利用Month。七月(给你7分) 而不是日历。七月(给你6分)。
(import java.time.*;)