How do I know if a given year is a leap year?

The example How do I check if a year is a leap year? use the java.util.Calendar object to determine if a given year is a leap year. That was the way to do it using the old API before we have the Date and Time API introduced in Java 8.

Now, in the Java 8 API we can check if a given year is a leap year using a couple of ways. We can determine if a given date is in a leap year by calling the isLeapYear() method of the java.time.LocalDate class. While using the java.time.Year class we can check is the given year if a leap year using the isLeap() method.

The following code snippet will show you how to do it:

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.Month;
import java.time.Year;
import java.time.temporal.ChronoField;

public class YearIsLeapExample {
    public static void main(String[] args) {
        // Using the java.time.LocalDate class.
        LocalDate now = LocalDate.now();
        boolean isLeap = now.isLeapYear();
        System.out.printf("Year %d, leap year = %s%n", now.getYear(), isLeap);

        LocalDate date = LocalDate.of(2020, Month.JANUARY, 1);
        isLeap = date.isLeapYear();
        System.out.printf("Year %d, leap year = %s%n", date.getYear(), isLeap);

        // Using the java.time.Year class.
        Year year = Year.now();
        isLeap = year.isLeap();
        System.out.printf("Year %d, leap year = %s%n", year.getValue(), isLeap);

        Year anotherYear = Year.of(2020);
        isLeap = anotherYear.isLeap();
        System.out.printf("Year %d, leap year = %s%n", anotherYear.get(ChronoField.YEAR), isLeap);
    }
}

The code snippet will print out the following result:

Year 2021, leap year = false
Year 2020, leap year = true
Year 2021, leap year = false
Year 2020, leap year = true

How do I parse a string into date and time?

In this code snippet you will learn how to parse a string into an instance of LocalDate, LocalTime and LocalDateTime. All of these classes provide a parse() method that accept an argument of string that represent a valid date and time information and convert it into the corresponding object.

If the string passed into the parse() method is not representing a valid date or time information this method throws a RuntimeException of type DateTimeParseException exception. If you want to handle this exception then you should wrap your code inside a try-catch block.

Let’s see the code snippet below as an example:

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeParseException;

public class DateTimeParseDemo {
    public static void main(String[] args) {

        // Parse string "2021-09-12" into LocalDate instance.
        LocalDate date = LocalDate.parse("2021-09-12");

        // Parse string "17:51:15: into LocalTime instance.
        LocalTime time = LocalTime.parse("17:51:15");

        // Parse string "2021-09-12T17:51:15" into LocalDateTime instance.
        LocalDateTime dateTime = LocalDateTime.parse("2021-09-12T17:51:15");

        System.out.println("date     = " + date);
        System.out.println("time     = " + time);
        System.out.println("dateTime = " + dateTime);

        try {
            // When the string cannot be parsed, a RuntimeException of type
            // DateTimeParseException will be thrown.
            LocalDate date1 = LocalDate.parse("2021-02-31");
            System.out.println("date1     = " + date1);
        } catch (DateTimeParseException e) {
            e.printStackTrace();
        }
    }
}

Running this code snippet will produce the following result:

date     = 2021-09-12
time     = 17:51:15
dateTime = 2021-09-12T17:51:15
java.time.format.DateTimeParseException: Text '2021-02-31' could not be parsed: Invalid date 'FEBRUARY 31'
    at java.base/java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:2023)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1958)
    at java.base/java.time.LocalDate.parse(LocalDate.java:430)
    at java.base/java.time.LocalDate.parse(LocalDate.java:415)
    at org.kodejava.datetime.DateTimeParseDemo.main(DateTimeParseDemo.java:27)
Caused by: java.time.DateTimeException: Invalid date 'FEBRUARY 31'
    at java.base/java.time.LocalDate.create(LocalDate.java:461)
    at java.base/java.time.LocalDate.of(LocalDate.java:273)
    at java.base/java.time.chrono.IsoChronology.resolveYMD(IsoChronology.java:654)
    at java.base/java.time.chrono.IsoChronology.resolveYMD(IsoChronology.java:126)
    at java.base/java.time.chrono.AbstractChronology.resolveDate(AbstractChronology.java:442)
    at java.base/java.time.chrono.IsoChronology.resolveDate(IsoChronology.java:586)
    at java.base/java.time.chrono.IsoChronology.resolveDate(IsoChronology.java:126)
    at java.base/java.time.format.Parsed.resolveDateFields(Parsed.java:365)
    at java.base/java.time.format.Parsed.resolveFields(Parsed.java:272)
    at java.base/java.time.format.Parsed.resolve(Parsed.java:259)
    at java.base/java.time.format.DateTimeParseContext.toResolved(DateTimeParseContext.java:331)
    at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2058)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1954)
    ... 3 more

As we can see from the output above, parsing a text string of "2021-02-31" give us a DateTimeParseException because the 31st of February is not a valid date.

How do I use java.time.LocalDateTime class?

The java.time.LocalDateTime class represents information of both date and time without time-zone. We can create LocalDateTime using the available static factory method such as the of() method or by combining an instance of LocalDate and LocalTime.

The following code snippet will show you both ways. First we begin with using the of() method where we can pass arguments such as the year, month, day, hour, minute and second. On the following line we also use the of() method but this time we pass an instance of LocalDate and LocalTime as the arguments.

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;

public class LocalDateTimeDemo {
    public static void main(String[] args) {
        // Creates an instance of LocalDateTime using of()
        // static factory method with full date and time arguments.
        LocalDateTime dateTime =
                LocalDateTime.of(2021, Month.SEPTEMBER, 11, 16, 15, 15);
        System.out.println("dateTime  = " + dateTime);

        // Combines LocalDate and LocalTime to creates a new
        // instance of LocalDateTime.
        LocalDate date = LocalDate.now();
        LocalTime time = LocalTime.now();
        LocalDateTime dateTime2 = LocalDateTime.of(date, time);
        System.out.println("dateTime2 = " + dateTime2);

        // Creates LocalDateTime from LocateDate with time using
        // atTime() method.
        LocalDateTime dateTime3 = date.atTime(16, 15, 15);
        LocalDateTime dateTime4 = date.atTime(time);
        System.out.println("dateTime3 = " + dateTime3);
        System.out.println("dateTime4 = " + dateTime4);

        // Creates LocalDateTime from LocalTime with date using
        // atDate() method.
        LocalDateTime dateTime5 = time.atDate(date);
        System.out.println("dateTime5 = " + dateTime5);

        // Obtains LocalDate and LocalTime from LocalDateTime using
        // toLocalDate() and toLocalTime() methods.
        LocalDate date1 = dateTime5.toLocalDate();
        LocalTime time1 = dateTime5.toLocalTime();
        System.out.println("date1 = " + date1);
        System.out.println("time1 = " + time1);
    }
}

We can also create an instance of LocalDateTime by using the LocalDate‘s atTime() method or LocalTime‘s atDate() method as seen in the code snippet above.

On the very end of the code snippet you can see how to obtain a LocalDate or LocalTime information from an instance of LocalDateTime using the toLocalDate() and toLocalTime() method.

Running this code snippet will give you the following result:

dateTime  = 2021-09-11T16:15:15
dateTime2 = 2021-11-16T07:06:36.460459800
dateTime3 = 2021-11-16T16:15:15
dateTime4 = 2021-11-16T07:06:36.460459800
dateTime5 = 2021-11-16T07:06:36.460459800
date1 = 2021-11-16
time1 = 07:06:36.460459800

How do I use java.time.LocalTime class?

An instance of LocalTime class represent information about time. It doesn’t contain information about date. To create an instance of this class we can use the of() static factory method. There are two types of this method. The first one accept two arguments, hour and minute. The second type also accept the second as the arguments.

The code snippet below show you how to create an instance of LocalTime and how to obtain its values.

package org.kodejava.datetime;

import java.time.LocalTime;

public class LocalTimeDemo {
    public static void main(String[] args) {
        LocalTime time = LocalTime.of(15, 5, 30);

        int hour = time.getHour();
        int minute = time.getMinute();
        int second = time.getSecond();

        System.out.println("hour = " + hour);
        System.out.println("minute = " + minute);
        System.out.println("second = " + second);
    }
}

To get the values from the LocalTime object we can use the getHour(), getMinute() and getSecond() methods to get hour, minute and second respectively.

Running this snippet result the following output:

hour = 15
minute = 5
second = 30

You can also use the get() method to read values represented by the LocalTime object. We call this method with the temporal field that we want to read. The following code snippet will give you the same result as the previous code, only this time we use the get() method.

int hour = time.get(ChronoField.HOUR_OF_DAY);       
int minute = time.get(ChronoField.MINUTE_OF_HOUR);  
int second = time.get(ChronoField.SECOND_OF_MINUTE);

System.out.println("hour   = " + hour);             
System.out.println("minute = " + minute);           
System.out.println("second = " + second);

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);