Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Calendar, getting current month value, clarification needed

Tags:

java

calendar

On November 1st ..

  Calendar.getInstance().get(Calendar.MONTH); // prints 10 (October)

It would make sense if we start with 0, but it appears that we do not

  Calendar.getInstance().get(Calendar.JANUARY); // prints 1

What am i missing please?

like image 517
James Raitsev Avatar asked Nov 01 '12 16:11

James Raitsev


People also ask

How do you find the current month and year from a calendar class?

The now() method of this class obtains the current date from the system clock. The getYear() method returns an integer representing the year filed in the current LocalDate object. The getMonth() method returns an object of the java. timeMonth class representing the month in the LocalDate object.

What is calendar getInstance () in Java?

The getInstance() method in Calendar class is used to get a calendar using the current time zone and locale of the system. Syntax: public static Calendar getInstance() Parameters: The method does not take any parameters. Return Value: The method returns the calendar.

How do you check if a date is in a month Java?

YearMonth ref = YearMonth. from(LocalDate. now()); return Month. from(temporal) == Month.

Is calendar deprecated in Java?

Calendar , too) are not officially deprecated, just declared as de facto legacy.


2 Answers

Months in Java Calendar are 0-indexed. Calendar.JANUARY isn't a field so you shouldn't be passing it in to the get method.

like image 113
Chris Avatar answered Sep 22 '22 09:09

Chris


as others said Calendar.MONTH returns int and is zero indexed.

to get the current month as a String use SimpleDateFormat.format() method

Calendar cal = Calendar.getInstance();
System.out.println(new SimpleDateFormat("MMM").format(cal.getTime()));

returns NOV
like image 27
PermGenError Avatar answered Sep 19 '22 09:09

PermGenError