且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java - 从日期中减去天数

更新时间:2023-11-29 13:28:40

你知道吗,在 Java 中,月份 1 实际上是二月?

Did you know that, in Java, month 1 is actually February?

Date februaryTheFirst = new Date(2012,1,1); // equals 2012-02-01

这可以解释您所看到的.如果你想实例化 2012-01-01 ,你应该这样做:

This might explain what you are seeing. If you want to instantiate 2012-01-01 instead, you should do:

Date firstDayOf2012 = new Date(2012,0,1); // this is 2012-01-01

在处理 Calendar 时会发生完全相同的事情:

Exactly the same thing happens when dealing with Calendar:

Calendar.getInstance().set(2012,0,1); // 2012-01-01

请务必查看 Date(int, int, int) 的文档和 Calendar.set(int, int, int).此外,您可以检查解析字符串的方式.如果您使用 SimpleDateFormat.parse(...),事情会变得更容易.

Be sure to check the documentation for Date(int, int, int) and Calendar.set(int, int, int). Also, you could check the way you are parsing the string. If you use SimpleDateFormat.parse(...), things can be easier.

很奇怪,不是吗?想想看……就像一个有趣的事实,IntelliJ 的文档用 @MagicConstant 注释了第二个参数月,以提醒程序员发生了一些非常奇怪的事情.

Strange, isn't it? Go figure... Just as a fun fact, IntelliJ's documentation annotates this second parameter, month, with @MagicConstant, to remember the programmer that there's something very strange going on.