問題描述
我正在嘗試從最初以字符串形式出現(xiàn)的日期中減去 5 天.
I'm trying to subtract 5 days from a date which comes in as a string initially.
我查看了有關(guān)此主題的其他一些帖子,但我從代碼中得到的結(jié)果總是不正確的.主要問題是,例如,減去天數(shù)時,年份值似乎沒有改變 - 2012-01-01 minus 5 days give me 'Jan 27 2012'
使用此代碼 -
I have had a look at some of the other posts on this subject but the result i get from the code is always incorrect. The main problem is that the year value does not seem to change when the days are subtracted for example - 2012-01-01 subtract 5 days gives me 'Jan 27 2012'
using this code -
cal.add(Calendar.DATE, -5);
請幫忙.
推薦答案
你知道嗎,在 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 ,你應(yīng)該這樣做:
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
時會發(fā)生完全相同的事情:
Exactly the same thing happens when dealing with Calendar
:
Calendar.getInstance().set(2012,0,1); // 2012-01-01
請務(wù)必查看 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
注釋了第二個參數(shù)月,以提醒程序員發(fā)生了一些非常奇怪的事情.
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.
這篇關(guān)于Java - 從日期中減去天數(shù)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!