Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 399
jc k Avatar asked Nov 18 '25 21:11

jc k


1 Answers

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

like image 73
MadProgrammer Avatar answered Nov 21 '25 10:11

MadProgrammer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!