java日历添加不起作用

时间:2015-05-20 12:02:50

标签: java date calendar add

我使用add方法将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
}

1 个答案:

答案 0 :(得分:4)

这个过程很好......

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表示“天”(周一至周日),因此在任何日期添加7将为您提供相同的“DAY_OF_WEEK”。

也许您打算使用DATE而不是

tmpDay = startCal.get(Calendar.DATE);

作为旁注,我建议您使用Java 8的新时间API或Joda-Time超过Calendar,您通常会发现它更简单,但那就是我