java 日历添加不工作

java calendar add is not working

我使用添加方法向日历添加了 3 天。

但我发现它不能正常工作。

Calendar.add(Calendar.DATE, 7);

请让我知道哪里出了问题。

while(dateIdx < nowDate)
{
    int tmpYear = startCal.get(Calendar.YEAR);
    int tmpMonth = startCal.get(Calendar.MONTH)+1;
    int tmpDay = startCal.get(Calendar.DAY_OF_WEEK);

    System.out.println(+tmpYear+tmpMonth+tmpDay+ "- "+tmpYear+tmpMonth+(tmpDay+6));
    startCal.add(Calendar.DATE, 7); //used add method here
    tmpYear = startCal.get(Calendar.YEAR);
    tmpMonth = startCal.get(Calendar.MONTH)+1;
    tmpDay = startCal.get(Calendar.DAY_OF_WEEK);
    dateIdx = tmpYear*10000 + tmpMonth*100 +tmpDay; //it is not incorrect result
}

进程运行良好...

Calendar startCal = Calendar.getInstance();
int tmpYear = startCal.get(Calendar.YEAR);
int tmpMonth = startCal.get(Calendar.MONTH) + 1;
int tmpDay = startCal.get(Calendar.DAY_OF_WEEK);

System.out.println(tmpYear + "/" + tmpMonth + "/" + tmpDay);
System.out.println(startCal.getTime());
startCal.add(Calendar.DATE, 7); //used add method here
tmpYear = startCal.get(Calendar.YEAR);
tmpMonth = startCal.get(Calendar.MONTH) + 1;
tmpDay = startCal.get(Calendar.DAY_OF_WEEK);

System.out.println(tmpYear + "/" + tmpMonth + "/" + tmpDay);
System.out.println(startCal.getTime());

哪个输出...

2015/5/4
Wed May 20 22:07:14 EST 2015
2015/5/4
Wed May 27 22:07:14 EST 2015

DAY_OF_WEEK 表示它是 "day"(周一到周日),因此将 7 加到任何日期都会得到相同的 `DAY_OF_WEEK.

也许您打算改用 DATE

tmpDay = startCal.get(Calendar.DATE);

作为旁注,我鼓励您使用 Java 8 的新时间 API 或 Joda-Time 而不是 Calendar,您通常会发现它更简单,但是就是我