小小的腦袋有一個大大的疑惑??Calendar告訴我6月有31號

小小的腦袋有一個大大的疑惑??6月有31日嗎?

小幸今天在用java刷算法題的時候,偶然間用到Calendar這個類,想借用他的日曆功能計算某一天後的n天的日期,誰知卻有驚奇的發現,直接上代碼。

import java.util.Calendar;

public class Main {
	public static void main(String[] args) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(2020, 6, 1);
//		calendar.set(2020, 2, 1);
		calendar.add(Calendar.DATE, 30);
		System.out.println(calendar.get(Calendar.YEAR)+"-"+calendar.get(Calendar.MONTH)
				+"-"+calendar.get(Calendar.DATE));
	}
}

本例中,我想計算2020年6月1日後的第30天的日期,正確的答案應該是2020-7-1。萬萬沒想到,這段代碼給出的答案卻是2020-6-31,頓時我就納悶了,6月是大月?有31號?我不知道這是我知識的盲區,還是該類在處理的時候沒有考慮到這些呢?後邊小幸還測試了2月,發現竟然會輸出2020-2-31,真的是刷新我的認識。於是我修改增加的天數,發現天數改動之後,其間只會有這樣的一個日期出錯,下一年遇到改天的時候會正確轉爲下一月,這就讓我頓生疑惑,難到api指定了最多隻能錯一次?
爲了搞明白這是爲何,到底是認知問題還是有意爲之,我進一步查看了Calendar這個類,發現這是個抽象類,add方法調用roll方法,而roll方法在聲明的時候給出瞭如下注釋:

    /**
     * Adds or subtracts (up/down) a single unit of time on the given time
     * field without changing larger fields. For example, to roll the current
     * date up by one day, you can achieve it by calling:
     * <p>roll(Calendar.DATE, true).
     * When rolling on the year or Calendar.YEAR field, it will roll the year
     * value in the range between 1 and the value returned by calling
     * <code>getMaximum(Calendar.YEAR)</code>.
     * When rolling on the month or Calendar.MONTH field, other fields like
     * date might conflict and, need to be changed. For instance,
     * rolling the month on the date 01/31/96 will result in 02/29/96.
     * When rolling on the hour-in-day or Calendar.HOUR_OF_DAY field, it will
     * roll the hour value in the range between 0 and 23, which is zero-based.

大家注意一下如下注釋,大概意思是用月份或者日期去進行回滾(即增加/減少天數)可能會引起衝突,並且直接給出衝突例子。

When rolling on the month or Calendar.MONTH field, other fields like date might conflict and, 
need to be changed. For instance, rolling the month on the date 01/31/96 will result in 02/29/96.

那意思是api定義的時候就知道會出現這樣的問題,但是並沒有解決嗎?那小幸就納悶了,對於這種知道bug卻不解決bug的函數,留着的用處是爲何?
歡迎大家在留言區討論喲~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章