Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)
How do I get the month as an integer from a Date object (java.util.Date)?

1 Answer

0 votes
by (46k points)

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.

Browse Categories

...