Java: Get month Integer from Date
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.
java.util.Date date= new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
If you use Java 8 date api, you can directly get it in one line!
LocalDate today = LocalDate.now();
int month = today.getMonthValue();