In this short tutorial, we’ll look at how to extract the year, month and day from a given Date in Java.
We’ll be looking at how to extract these values using the legacy java.util.Date class and also by using the new date-time library of Java 8.
In Java 8, a whole new date and time library was introduced for a number of good reasons. Besides other advantages, the new library provides a better API for operations such as extracting Year, Month, Day etc. from given Date.
And, if you’re looking for a more detailed article on the new date-time library, have a look here.
2. Using Java 7
For a given java.util.Date to extract individual fields such as Year, Month, Day etc. the first step we need to do is to convert it to Calendar instance:
Date date = // the date instance Calendar calendar = Calendar.getInstance(); calendar.setTime(date);
Once we have a Calendar instance, we can directly invoke its get method and provide the specific field that we want to extract.
We can use constants present in Calendar to extract specific fields.
2.1. Get Year
To extract the year, we can invoke get by passing Calendar.YEAR as an argument:
2.2. Get Month
Similarly to extract the month, we can invoke get by passing Calendar.MONTH as an argument:
Please note that months in Calendar are zero-indexed; for January this method will return 0.
2.3. Get Day
Finally, to extract the day, we invoke get by passing Calendar.DAY_OF_MONTH as an argument:
3. Using Java 8
The new java.time package contains a number of classes that can be used for representing Date.
Each class differs by the additional information it stores in addition to the Date.
The basic LocalDate just contains the date information, while LocalDateTime contains date as well as time information.
Similarly, more advanced classes such as OffsetDateTime and ZonedDateTime contains additional information about offset from UTC and information about time-zone respectively.
In any case, all these classes support direct methods to extract Year, Month and Date information.
Let’s explore these methods to extract information from a LocalDate instance name localDate.
3.1. Get Year
To extract Year, LocalDate simply provides a getYear method:
3.2. Get Month
Similarly, to extract Month, we use getMonthValue API:
Unlike Calendar, Months in LocalDate are indexed from 1; for January this will return 1.
3.3. Get Day
Finally, to extract Day, we have getDayOfMonth method:
In this quick tutorial, we’ve explored how to extract integer values of Year, Month and Day from Date in Java.
We’ve shown how to extract these values using the old Date and Calendar classes as well as the new date-time library of Java8.
The complete source code for snippets used in this tutorial is available over at Github.