How do I get the month as an integer from a Date object (java.util.Date
)?
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.
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.
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.
java.util.Date date= new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(date); int month = cal.get(Calendar.MONTH);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With