Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calendar issue in Adding month +1 to to calendar month in Android

Tags:

java

date

android

I am using the following code

Calendar cal = Calendar.getInstance(); System.out.println("Before "+cal.getTime()); cal.set(Calendar.MONTH, 01); System.out.println("After "+cal.getTime()); 

the output is

Before Thu Jan 31 10:07:34 IST 2013 After Sun Mar 03 10:07:34 IST 2013 

for adding +1 to jan is giving mar month. may be it returning correct output if we add 30 days to present date. but i want to show feb month. can any body help me please..

like image 591
Naveen Avatar asked Jan 31 '13 04:01

Naveen


People also ask

How do I get the month of my first date Android?

text. SimpleDateFormat; ... Date currentMonth = new Date(); String yyyyMM = new SimpleDateFormat("yyyyMM").

How can I get current date and month in Android?

getInstance(). getTime(); System. out. println("Current time => " + c); SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy"); String formattedDate = df.


2 Answers

you can see the +1 to set field is adding 30 days date different to your dates(observed from your output.)

if you want months then use the code

Calendar cal = Calendar.getInstance(); System.out.println("Before "+cal.getTime());  //Before Thu Jan 31 10:16:23 IST 2013  cal.add(Calendar.MONTH, 1); System.out.println("After "+cal.getTime()); //After Thu Feb 28 10:16:23 IST 2013 
like image 192
Ram kiran Pachigolla Avatar answered Sep 18 '22 19:09

Ram kiran Pachigolla


You have to use add() like,

cal.add(Calendar.MONTH, 1); 

OUTPUT ->

Before Thu Jan 31 10:15:04 IST 2013 After Thu Feb 28 10:15:04 IST 2013 
like image 31
Lalit Poptani Avatar answered Sep 20 '22 19:09

Lalit Poptani