In this short tutorial, we'll learn how to extract the year, month, and day from a given Date in Java.
We'll discuss 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 a given Date.
For a more detailed article on the new date-time library, have a look here.
2. Using LocalDate
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 and time information.
Similarly, more advanced classes, such as OffsetDateTime and ZonedDateTime, contain additional information about offset from UTC and about time-zone, respectively.
In any case, all of these classes support direct methods to extract Year, Month, and Day information.
Let's explore these methods to extract information from a LocalDate instance named localDate.
2.1. Get Year
To extract Year, LocalDate simply provides a getYear method:
2.2. Get Month
Similarly, to extract Month, we'll use the getMonthValue API:
Unlike Calendar, Months in LocalDate are indexed from 1; for January, this will return 1.
2.3. Get Day
Finally, to extract Day, we have the getDayOfMonth method:
3. Using java.util.Date
For a given java.util.Date, to extract individual fields such as Year, Month, Day etc., the first step we need to do is convert it to a 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.
3.1. Get Year
To extract the year, we can invoke get by passing Calendar.YEAR as an argument:
3.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.
3.3. Get Day
Finally, to extract the day, we invoke get by passing Calendar.DAY_OF_MONTH as an argument:
In this brief article, we explored how to extract integer values of Year, Month, and Day from Date in Java.
We learned 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 the snippets used in this article is available over at Github.