【问题标题】:Day and month incorrect when setting next day of date using Calendar使用日历设置日期的下一天时,日期和月份不正确
【发布时间】:2014-08-28 08:20:48
【问题描述】:
//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?

【问题讨论】:

标签: java date calendar date-format


【解决方案1】:

原因是月份是从零开始的索引,即它们从 0 而不是 1 开始,所以一月是 0,二月是 1,三月是 2,.....十二月是 11

来自Oracle docs

一个月用一个从0到11的整数表示; 0 是一月,1 是 二月,依此类推;因此 11 是 12 月。

编辑:-

试图给出月份以零开头的原因。 在time.h 中定义的tm 结构有一个整数字段tm_mon,范围为0-11,所以我猜这是取自C 语言。另一个原因可能听起来很奇怪,但可能是因为我们有月份的名称,但是对于天(1,2,3...30,31)我们没有任何名称

【讨论】:

    猜你喜欢
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多