Learn to get the year, month and day from a given date in Java using the new LocalDate
class as well as legacy java.util.Date
class.
1. Get Day, Month and Year since Java 8
The new Date Time API, added in Java 8, has several classes capable of storing a date (day, month and year). A few of them are:
- LocalDate
- LocalDateTime
- ZonedDateTime
- OffsetDateTime
The above classes provide the methods to query the day, month and year information from a given instance.
- getYear() – returns the year as int value.
- getMonthValue() – returns the month as a number from 1 to 12.
- getDayOfMonth() – returns the int value for the day-of-month.
Java program to extract the day, month and year from a date in Java 8.
LocalDate today = LocalDate.now(); //23-Feb-022
int day = today.getDayOfMonth(); //23
int month = today.getMonthValue(); //2
int year = today.getYear(); //2022
We can invoke these same methods with LocalDateTime
and other classes as well. Except for LocalDate, other classes provide methods to extract hours, minutes and seconds.
2. Get Day, Month and Year from java.util.Date
Directly pulling the day, month and year information from a java.util.Date instance is NOT possible. We must convert the Date to Calendar instance.
The Calendar
class provides the following constants that we can use to query the date parts.
- Calendar.DAY_OF_MONTH – field indicating the day of the month.
- Calendar.MONTH – field indicating the month from 0 to 11.
- Calendar.YEAR – field indicating the year.
Java program to extract the day, month and year from a Date using Calendar.
Date date = new Date(); //23-Feb-022
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int day = calendar.get(Calendar.DAY_OF_MONTH); //23
int month = calendar.get(Calendar.MONTH); //1
int year = calendar.get(Calendar.YEAR); //2022
3. Conclusion
In this Java tutorial, we learned to extract the integer values for the day, month and year information from new date API classes and the old legacy Java classes.
It is highly recommended to use the new Date API as it provides many specialized classes and methods for all kinds of usecases.
Happy Learning !!
Comments