Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Get month Integer from Date

How do I get the month as an integer from a Date object (java.util.Date)?

like image 509
Muhd Avatar asked Aug 24 '11 22:08

Muhd


People also ask

How do you get month and year from a date object in Java?

The getDayOfMonth() method returns the day represented by the given date, getMonth() method returns the month represented by the given date, and getYear() method returns the year represented by the given date.

How do I get a month from LocalDate?

LocalDate getMonth() method in JavaThe getMonth() method of LocalDate class in Java gets the month-of-year field using the Month enum. Parameter: This method does not accepts any parameter. Return Value: The function returns the month of the year.

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.


2 Answers

java.util.Date date= new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(date); int month = cal.get(Calendar.MONTH); 
like image 73
adarshr Avatar answered Sep 22 '22 06:09

adarshr


java.time (Java 8)

You can also use the java.time package in Java 8 and convert your java.util.Date object to a java.time.LocalDate object and then just use the getMonthValue() method.

Date date = new Date(); LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); int month = localDate.getMonthValue(); 

Note that month values are here given from 1 to 12 contrary to cal.get(Calendar.MONTH) in adarshr's answer which gives values from 0 to 11.

But as Basil Bourque said in the comments, the preferred way is to get a Month enum object with the LocalDate::getMonth method.

like image 20
Ortomala Lokni Avatar answered Sep 22 '22 06:09

Ortomala Lokni