【发布时间】: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?
【问题讨论】:
-
您是否知道基于日期的月份为零?
-
这是一个愚蠢的设计决定。一月是 0 月而不是 1 月,二月是 1 月而不是 2 月,依此类推...
-
天从 1 开始计算,月份从 0 开始计算。第一天是 1,但第一个月(一月)是 0。
-
如果 java 8,请考虑
java.time包中的类型。如果没有,请考虑 joda time。这些日期和时间 API 的惊喜要少得多。
标签: java date calendar date-format