Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calendar.MONTH gives wrong value

I'm trying to get the actual month from the Calendar using the following:

Calendar c = Calendar.getInstance();          
String time = String.valueOf(c.get(Calendar.MONTH));

According the system settings "Settings --> Date & Time" actual month is 10 while get(Calendar.MONTH) returns 09.

like image 835
XorOrNor Avatar asked Oct 13 '13 17:10

XorOrNor


People also ask

How do you set a calendar value?

set(int, int, int, int, int, int) method sets the values for the calendar fields YEAR, MONTH,DAY_OF_MONTH,HOUR_OF_DAY,MINUTE and SECOND.

Is calendar deprecated?

Calendar , too) are not officially deprecated, just declared as de facto legacy. The support of the old classes is still important for the goal of backwards compatibility with legacy code.

What is the difference between calendar and Gregorian calendar in java?

The major difference between GregorianCalendar and Calendar classes are that the Calendar Class being an abstract class cannot be instantiated. So an object of the Calendar Class is initialized as: Calendar cal = Calendar. getInstance();

What is GregorianCalendar in java?

GregorianCalendar is a concrete subclass of Calendar and provides the standard calendar system used by most of the world.


3 Answers

Keep in mind that months values start from 0, so October is actually month number 9.

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Calendar.html#MONTH

like image 179
ssantos Avatar answered Oct 31 '22 04:10

ssantos


Calendar.MONTH returns month which is zero based that is why it is giving 1 less than actual month Add 1 to get correct value

String time = String.valueOf(c.get(Calendar.MONTH)+1);
like image 42
Manishika Avatar answered Oct 31 '22 02:10

Manishika


Calendar.MONTH

returns

0 for 1st month (jan)
1 for 2nd month (feb)
.
.
11 for 12th month (dec)

Docs

So change your code to

String time = String.valueOf(c.get(Calendar.MONTH)+1);// added 1 
like image 39
Tarsem Singh Avatar answered Oct 31 '22 02:10

Tarsem Singh