Java 8 Date and Time API

JavaJavaBeginner
Practice Now

Introduction

Java 8 introduced the new Date and Time API which is inspired by the JodaTime library. It overcomes the drawbacks of the existing Date API. In this lab, we will learn how to use the new Date and Time API to manipulate dates and times.

Creating LocalDate Instances

The LocalDate class is used to represent a date in the standard ISO format (yyyy-mm-dd). It does not include time and does not support timezones.

We can create an instance of the LocalDate class by using the now() method. It will capture the current date according to the system's clock.

import java.time.LocalDate;

public class DateTimeExample {
    public static void main(String[] args) {
        LocalDate currentDate = LocalDate.now();
        System.out.println("Current Date: " + currentDate);
    }
}

Save and execute the code using the following command:

javac DateTimeExample.java && java DateTimeExample

We will see the output below:

Current Date: 2021-08-13

Parsing a Date String

We can create an instance of the LocalDate class using a string representation of a date.

import java.time.LocalDate;

public class DateTimeExample {
    public static void main(String[] args) {
        String str = "2021-08-13";
        LocalDate date = LocalDate.parse(str);
        System.out.println("Date: " + date);
    }
}

Save and execute the code using the following command:

javac DateTimeExample.java && java DateTimeExample

We will see the output below:

Date: 2021-08-13

Plus and Minus Methods

We can add or subtract days, months, or years from a date using the plusDays() or minusDays() method. We also have similar methods to alter months and years.

import java.time.LocalDate;

public class DateTimeExample {
    public static void main(String[] args) {
        LocalDate currDate = LocalDate.now();
        LocalDate yesterday = currDate.minusDays(1);
        LocalDate tomorrow = currDate.plusDays(1);

        System.out.println("Current Date: " + currDate);
        System.out.println("Tomorrow's Date: " + tomorrow);
        System.out.println("Yesterday's Date: " + yesterday);
    }
}

Save and execute the code using the following command:

javac DateTimeExample.java && java DateTimeExample

We will see the output below:

Current Date: 2021-08-13
Tomorrow's Date: 2021-08-14
Yesterday's Date: 2021-08-12

Getter Methods

The LocalDate class contains several getter methods to fetch different information from the LocalDate such as get day of week or day of month, etc.

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

public class DateTimeExample {
    public static void main(String[] args) {
        LocalDate currDate = LocalDate.now();
        DayOfWeek dayOfWeek = currDate.getDayOfWeek();
        int dayOfMonth = currDate.getDayOfMonth();
        int dayOfYear = currDate.getDayOfYear();

        System.out.println("Date: " + currDate);
        System.out.println("Day of Week: " + dayOfWeek);
        System.out.println("Day of Month: " + dayOfMonth);
        System.out.println("Day of Year: " + dayOfYear);
    }
}

Save and execute the code using the following command:

javac DateTimeExample.java && java DateTimeExample

We will see the output below:

Date: 2021-08-13
Day of Week: FRIDAY
Day of Month: 13
Day of Year: 225

Comparing Dates

We can compare dates by using the isBefore() and isAfter() methods to check which is greater.

import java.time.LocalDate;

public class DateTimeExample {
    public static void main(String[] args) {
        LocalDate currDate = LocalDate.now();
        LocalDate tomorrow = currDate.plusDays(1);
        LocalDate yesterday = currDate.minusDays(1);

        System.out.println("Current date is after yesterday's date: " + currDate.isAfter(yesterday));
        System.out.println("Current date is before tomorrow's date: " + currDate.isBefore(tomorrow));
    }
}

Save and execute the code using the following command:

javac DateTimeExample.java && java DateTimeExample

We will see the output below:

Current date is after yesterday's date: true
Current date is before tomorrow's date: true

Creating LocalTime Instances

To create a LocalTime instance, we can use the now() , of() , or parse() method. The now() method will use the system's clock to fetch the current time. The of() and parse() methods can create a LocalTime according to the parameters passed.

import java.time.LocalTime;

public class DateTimeExample {
    public static void main(String[] args) {
        LocalTime currentTime = LocalTime.now();
        LocalTime t1 = LocalTime.of(5, 32, 44);
        LocalTime t2 = LocalTime.parse("05:32:44");

        System.out.println(currentTime);
        System.out.println(t1);
        System.out.println(t2);
    }
}

Save and execute the code using the following command:

javac DateTimeExample.java && java DateTimeExample

We will see the output below:

17:43:08.749240
05:32:44
05:32:44

Plus and Minus Methods

We can use plus() and minus() methods to manipulate LocalTime instances.

import java.time.LocalTime;
import java.time.temporal.ChronoUnit;

public class DateTimeExample {
    public static void main(String[] args) {
        LocalTime t1 = LocalTime.of(5, 32, 44);
        LocalTime t2 = t1.plus(2, ChronoUnit.HOURS);
        LocalTime t3 = t1.minusMinutes(10);

        System.out.println(t1);
        System.out.println(t2);
        System.out.println(t3);
    }
}

Save and execute the code using the following command:

javac DateTimeExample.java && java DateTimeExample

We will see the output below:

05:32:44
07:32:44
05:22:44

Creating LocalDateTime Instances

The LocalDateTime class is a combination of the LocalDate and LocalTime classes. A LocalDateTime instance contains a date component and a time component.

import java.time.LocalDateTime;

public class DateTimeExample {
    public static void main(String[] args) {
        LocalDateTime currDateTime = LocalDateTime.now();
        LocalDateTime dt1 = LocalDateTime.of(2020, 8, 13, 5, 32);
        LocalDateTime dt2 = LocalDateTime.parse("2020-08-13T05:32");

        System.out.println(currDateTime);
        System.out.println(dt1);
        System.out.println(dt2);
    }
}

Save and execute the code using the following command:

javac DateTimeExample.java && java DateTimeExample

We will see the output below:

2021-08-13T17:46:48.837697
2020-08-13T05:32
2020-08-13T05:32

Working with Timezones

The classes discussed above do not support timezones. The ZonedDateTime class provides this functionality. We can use the ZoneId class to identify different time zones.

import java.time.ZonedDateTime;
import java.time.ZoneId;

public class DateTimeExample {
    public static void main(String[] args) {
        ZonedDateTime zdt = ZonedDateTime.now();
        ZoneId zoneTokyo = ZoneId.of("Asia/Tokyo");
        ZonedDateTime zdtT = ZonedDateTime.now(zoneTokyo);
        ZoneId zoneLondon = ZoneId.of("Europe/London");
        ZonedDateTime zdtL = ZonedDateTime.now(zoneLondon);

        System.out.println(zdt);
        System.out.println(zdtT);
        System.out.println(zdtL);
    }
}

Save and execute the code using the following command:

javac DateTimeExample.java && java DateTimeExample

We will see the output below:

2021-08-13T18:09:25.352237+05:30[Asia/Calcutta]
2021-08-13T21:39:25.356244+09:00[Asia/Tokyo]
2021-08-13T13:09:25.357316+01:00[Europe/London]

Formatting Dates

Java 8 provides a format() function to format a date to a string using a particular pattern.

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeExample {
    public static void main(String[] args) {
        LocalDateTime dateTime = LocalDateTime.now();
        String dateStr1 = dateTime.format(DateTimeFormatter.ISO_WEEK_DATE);
        String dateStr2 = dateTime.format(DateTimeFormatter.BASIC_ISO_DATE);
        String dateStr3 = dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        String dateStr4 = dateTime.format(DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm:ss"));

        System.out.println(dateStr1);
        System.out.println(dateStr2);
        System.out.println(dateStr3);
        System.out.println(dateStr4);
    }
}

Save and execute the code using the following command:

javac DateTimeExample.java && java DateTimeExample

We will see the output below:

2021-W32-5
20210813
2021-08-13T18:16:57.675704
13/08/2021 06:16:57

Summary

In this lab, we learned how to use the Java 8 Date and Time API to manipulate dates and times. We learned how to create instances of the LocalDate, LocalTime, and LocalDateTime classes, manipulate them using the plus() and minus() methods, and get information from them using getter methods. Additionally, we learned how to work with time zones using the ZonedDateTime class and format dates using the DateTimeFormatter class.

Other Java Tutorials you may like