英文:
Value of Date type is getting icremented by 1 month
问题
d1的值是2020-09-15
而不是2020-08-15
。
英文:
I am trying to take a variable of Date type . But output I am getting is automatically getting incremented by one month.
Here is what I am doing
Date d1 = new Date(2020,8,15);
System.out.println(d1);
d1's value is coming 2020-09-15
instead of 2020-08-15
.
答案1
得分: 1
很遗憾,月份的值从0
开始,这使得8
成为了使用过时 API(例如java.util.Date
)时的九月。
这意味着为了获得所期望的输出,您需要这样写(去掉前导零):
Date d1 = new Date(2020, 9, 15);
System.out.println(d1);
幸运的是,现在有java.time
!
您可以这样使用它:
public static void main(String[] args) {
LocalDate d1 = LocalDate.of(2020, 8, 15);
System.out.println(d1);
}
它会输出:
2020-08-15
英文:
Unfortunately, month values are starting at 0
, which makes an 8
be September when using the outdated API (e.g. java.util.Date
).
That means to get the desired output, you would have to write (without a leading zero)
Date d1 = new Date(2020, 9, 15);
System.out.println(d1);
Fortunately, there's java.time
now!
You can use it like this
public static void main(String[] args) {
LocalDate d1 = LocalDate.of(2020, 8, 15);
System.out.println(d1);
}
and it outputs
2020-08-15
答案2
得分: 0
Date
接受的月份范围是从0到11,而不是从1到12。因此,new Date(2020,08,15);
实际上表示的是 2020年9月15日
。
当日期被打印或格式化时,实际的月份是按照1到12的值来打印。
根据文档:
月份用从0到11的整数表示;0表示一月,1表示二月,以此类推;因此11表示十二月。
注意:始终优先使用java.time API,而不是java.util.Date
。
英文:
Date
takes months from 0 to 11 and not 1 to 12. So, new Date(2020,08,15);
is actually 15th September 2020
And when date is printed/formatted, actual month is printed (values 1 to 12).
According to docs
> A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.
Note : Always prefer java.time API over java.util.Date
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论