Intellipaat 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.

Related questions

0 votes
2 answers
0 votes
2 answers

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...