Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a day to a Calendar in Android fails on 31st

Tags:

Assume currently the date is the 28th of May. If I call the following commands in order the output becomes

cal.add(Calendar.DATE, 1);  // Day = 29
cal.add(Calendar.DATE, 1);  // Day = 30
cal.add(Calendar.DATE, 1);  // Day = 31
cal.add(Calendar.DATE, 1);  // Day = 31
cal.add(Calendar.DATE, -1); // Day = 29

Why is this not jumping into the next month? And why is it stuck at the 31st (but when you minus one it jumps to 29)?

like image 415
dinesh707 Avatar asked Aug 09 '12 11:08

dinesh707


People also ask

How to add 1 DAY to Calendar in android?

Calendar cal = Calendar. getInstance(); cal. add(Calendar. HOUR_OF_DAY, 24);


2 Answers

You can easily do this in two simple ways my friend. First one is:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, 1);

and the second one is:

Calendar cal = Calendar.getInstance(); 
cal.add(Calendar.HOUR_OF_DAY, 24);

I think you would like to find this thing. Thanks.

like image 148
Satyaki Mukherjee Avatar answered Sep 21 '22 15:09

Satyaki Mukherjee


When you add 1 to the Calendar.DATE field, it should increment the month as well when the end of the month is reached (31 in the case for May) so that you wrote doesn't make sense. Debug it and make sure the day value is indeed what you think it is

like image 36
IncrediApp Avatar answered Sep 17 '22 15:09

IncrediApp