Java LocalDate
Jakob Jenkov |
The LocalDate
class in the Java 8 date time API represents a local date which is a date without time
zone information. A local date could be a birthdate or official holiday etc. which relates to a specific day of the
year - not the precise time of that day (the moment the day starts).
The LocalDate
Java class is located in the java.time
package, so its fully qualified
class name is java.time.LocalDate
. LocalDate
instances are immutable, so all
calculations on a LocalDate
return a new LocalDate
.
Creating a LocalDate
You can create a LocalDate
in several ways. The first way is to obtain a LocalDate
corresponding to the local date of today. Here is an example of creating a LocalDate
using the
now()
method:
LocalDate localDate = LocalDate.now();
Another way to create a LocalDate
is to create it from year, month and day information, like this:
LocalDate localDate2 = LocalDate.of(2015, 12, 31);
The LocalDate
's of()
method creates a LocalDate
instance representing a
specific day of a specific month of a specific year, but without time zone information.
Accessing the Date Information of a LocalDate
You can access the date information of a LocalDate
using these methods:
getYear()
getMonth()
getDayOfMonth()
getDayOfWeek()
getDayOfYear()
Here is an example illustrating the use of these methods:
int year = localDate.getYear(); Month month = localDate.getMonth(); int dayOfMonth = localDate.getDayOfMonth(); int dayOfYear = localDate.getDayOfYear(); DayOfWeek dayOfWeek = localDate.getDayOfWeek();
Notice how the getMonth()
and getDayOfWeek()
methods return an enum
instead of an int
. From these enums you can obtain their information as int
values
by calling their getValue()
methods.
LocalDate Calculations
You can perform a set of simple date calculations with the LocalDate
class using one or more
of the following methods:
plusDays()
plusWeeks()
plusMonths()
plusYears()
minusDays()
minusWeeks()
minusMonths()
minusYears()
Here are a few LocalDate
calculation examples to give you an idea of how these date calculation
methods work:
LocalDate localDate = LocalDate.of(2015, 12, 31); LocalDate localDate1 = localDate.plusYears(3); LocalDate localDate2 = localDate.minusYears(3);
The first line creates a new LocalDate
. The second line creates a new LocalDate
which represents the same date as the first, but 3 years later. The third line creates a new LocalDate
object which represents the same date as the first, but 3 years earlier.
Tweet | |
Jakob Jenkov |