How do I use java.time.LocalDate class?

JDK8’s LocateDate class is a class that represent information about date. It doesn’t include information about time of day, and it also doesn’t have information about time-zone. An instance of this class is an immutable object.

To create an instance of LocateDate class we can use the of() static method factory. We pass arguments such as the year, month and day into this static factory method. The value for month can be an integer between 1 and 12, or you use the value specified by the java.time.Month enum, such as Month.JANUARY.

The code snippet below show you how to use the LocalDate class.

package org.kodejava.datetime;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;

public class LocalDateDemo {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2014, 9, 7);

        int year = date.getYear();
        Month month = date.getMonth();
        int day = date.getDayOfMonth();

        DayOfWeek dow = date.getDayOfWeek();
        int monthLength = date.lengthOfMonth();
        boolean leapYear = date.isLeapYear();

        System.out.println("Year         = " + year);
        System.out.println("Month        = " + month);
        System.out.println("Day          = " + day);
        System.out.println("Dow          = " + dow);
        System.out.println("Month Length = " + monthLength);
        System.out.println("Leap Year    = " + leapYear);
    }
}

As you can see from the code snippet above, the LocalDate class also provide some methods to get the value from the LocateDate instance. For example, you can obtain the year of the date using the getYear() method. To get the month we can use the getMonth() method which will return the Month enum. And to get the day we can use the getDayOfMonth() method.

We can also get information such as the length of the month and check if the year represented by this LocalDate is a leap year. Running the code snippet above will give you the following result:

Year         = 2014
Month        = SEPTEMBER
Day          = 7
Dow          = SUNDAY
Month Length = 30
Leap Year    = false

Beside using the methods shown above to access values from a LocalDate instance we can also use TemporalField as demonstrated in the code snippet below. Here we call the get() method and pass a temporal field that we want to read using the ChronoField enumeration. This enum implements the TemporalField interface.

int year = date.get(ChronoField.YEAR);
int month = date.get(ChronoField.MONTH_OF_YEAR);
int day = date.get(ChronoField.DAY_OF_MONTH);

System.out.println("year  = " + year);
System.out.println("month = " + month);
System.out.println("day   = " + day);
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.