Back
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();
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.
31k questions
32.8k answers
501 comments
693 users