jc k
jc k

Reputation: 223

java calendar add is not working

I used add method to add 3 days to calendar.

but I found that It is not working correctly.

Calendar.add(Calendar.DATE, 7);

please let me know what is wrong.

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
}

Upvotes: 3

Views: 3604

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347204

The process is working just fine...

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());

Which outputs...

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 indicates the "day" it is (Monday through Sunday), so adding 7 to any date will give you the same `DAY_OF_WEEK.

Perhaps you meant to use DATE instead

tmpDay = startCal.get(Calendar.DATE);

As a side note, I would encourage you to make use Java 8's new Time API or Joda-Time over Calendar, you'll generally find it simpler, but that's me

Upvotes: 4

Related Questions