Introduction to Date Time API in Java 8

Work with time and date using the date-time API, new in java 8.

“Never tell the truth to people who are not worthy of it.”
― Mark Twain

1. Introduction

Java 8 provides a new package for date, time and calendar calculations as an improvement over the earlier Date and Calendar classes. This is called the Date-Time API. Let us learn how to use this API.

2. DateTimeFormatter

The class DateTimeFormatter fulfils functionality similar to what was previously provided by SimpleDateFormat. Here is how you can create a formatter in a manner similar to SimpleDateFormat.

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss a VV");

Here is how you can format a time instance.

ZonedDateTime t = ZonedDateTime.now();
System.out.println(fmt.format(t));
# prints
2017-11-17 12:49:09 AM US/Eastern

3. ZoneId

The ZoneId class represents a time-zone ID, for example: US/Eastern. It allows you to work directly with the zone.

To find out all the supported time zones, you can do the following:

ZoneId
    .getAvailableZoneIds()
    .stream()
    .sorted()
    .forEach(System.out::println);
// prints
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmara
Africa/Asmera
...

4. LocalDate

LocalDate represents just the date without reference to any time zone.

System.out.println("Today -> " + LocalDate.now());
// prints
Today -> 2017-11-17

Last day of the month:

System.out.println(today.with(TemporalAdjusters.lastDayOfMonth()));
// prints
2017-11-30

Or first day of the next month:

System.out.println(today.with(TemporalAdjusters.firstDayOfNextMonth()));
// prints
2017-12-01

5. LocalTime

A LocalTime object represents time without reference to any time zone.

LocalTime now = LocalTime.now();
System.out.println("Now -> " + now);
// prints
Now -> 09:55:48.952

This class provides easy methods to add hours, minutes or seconds to the value.

System.out.println("+6 hours -> " + now.plusHours(6));
Now -> 15:55:48.952

6. ZonedDateTime

The class ZonedDateTime represents all the date and time fields at a specified locale. It can convert time and date from one time zone another.

Convert date and time from zone to another.

ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("US/Eastern"));

Create from a LocalDate, LocalTime and a zone:

LocalDate today = LocalDate.now();
LocalTime time = LocalTime.now();
ZoneId zone = ZoneId.of("US/Eastern");
ZonedDateTime zdt = ZonedDateTime.of(today, time, zone);

Conclusion

We learnt the basics of using the Date-Time API in Java 8. There are several separate classes for managing several aspects of date and time, including LocalDate, LocalTime, etc. Time zones are handled by ZoneId and time in a specific time zone is represented by ZonedDateTime.