簡體   English   中英

使用日歷設置日期的第二天時,日期和月份不正確

[英]Day and month incorrect when setting next day of date using Calendar

//fetch date and convert to date type
String DateString = Integer.toString(getDay()) + "/" + Integer.toString(getMonth()) + "/" + Integer.toString(getYear());
DateFormat parser = new SimpleDateFormat("dd/MM/yyyy"); //current format of date
Date date = (Date) parser.parse(DateString); //convert string to date
//calculate next day
Calendar cal = Calendar.getInstance();
cal.setTime(date); //set calendar time to chosen date
cal.add(Calendar.DATE, 1); //add 1 day to calendar date
//set object to next day
parser.format(cal.getTime()); //set format to dd/MM/yyyy
setDay(cal.get(cal.DAY_OF_MONTH));
setMonth(cal.get(cal.MONTH));
setYear(cal.get(cal.YEAR));

我將日期設定為2002年10月23日。我想使用上述方法將其設置為第二天。 它顯示的是2002年9月24日而不是2002年10月24日。為什么它在當天增加1並從月中刪除1?

原因是月份是基於零的指數,即,它們從0開始而不是1,因此1月是0,2月是1,3月是2和...... Decemeber是11

來自Oracle文檔

一個月由0到11的整數表示; 0是1月,1是2月,依此類推; 因此11月是12月。

編輯:-

試圖說明為什么幾個月從零開始的原因。 time.h中定義的tm結構有一個整數字段tm_mon ,范圍為0-11,所以我猜這是從C語言中獲取的。 另一個可能聽起來很奇怪的原因,但可能是因為我們有月份的名稱,但有幾天(1,2,3 ...... 30,31),我們沒有任何名字

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM