Introduction

Greetings!

Since Java 8, Oracle completely rebuilt its Date/Time API. The new API is supposed to replace the old one.

The new API which is located in the package is thread-safe because most of the new classes are immutable, meaning that, after the object is constructed, it cannot be modified. This is especially useful when working in a multi-threaded environment where issues like thread interference and data corruption cannot happen thanks to immutability.

This article shows how to work with the new API.

Creating Dates and Times

Java lets us create dates and times using static factory methods. Note that you cannot create date and time objects using a constructor (you can do so with the old API, but you shouldn’t) because it is made private.

Creating dates and times is straightforward; you’ll notice a pattern for creating dates and times:

LocalDate

You create a by using one of its static factory methods:

Note that month indexes are one-based.

LocalTime

Similarly, you create a object like so:

The second line output a representation of , which represents

LocalDateTime

The class represents date and time combined. You can create it with:

Note that in the output date and time are separated with a .

ZonedDateTime

Use this class if you want to express in a date and time in a specific timezone. for example:

The format of the output consists of followed by the .

Manipulating Dates and Times

You these methods return a LocalDate object. Therefore, you can chain them:

Using the same pattern, you can subtract dates/times from , , and using method.

Periods and Durations

Periods

You create a period from the class. This class represents the amount of time in years, months, and days. These examples demonstrate the typical ways you would create a :

These static factory methods are self-explanatory; they create an immutable Period instance.

In the output, the letter stands for Period, for years, for months, and for days.

Note that you cannot chain methods as you’ve seen in the example when you create because these methods are static, If you chain them you’ll get unexpected behavior:

Remember that a cannot be be used with some objects. Let’s look at some code:

Durations

You create a duration form the class. This class represents the amount of time in seconds and nanoseconds. It can also be expressed using other duration-based units, such as minutes and hours. These examples demonstrate the typical ways you would create a :

Alternatively, you can create a Duration using the following method:

This method takes 5 as an amount and a unit that the duration is measured in.

Working with Instants

You create an instant from the class. This class represents a single instantaneous point on the time-line in the GMT since January 1, 1970 (1970–01–01T00:00:00Z), a.k.a the EPOCH. It may come in handy when you want to record event timestamps in the program. These examples demonstrate the typical ways you would create an :

Note that the output of follows the ISO-8601 standard.

As you can see, when Java invoked it created an object from object and converted the time from US/Eastern timezone to GMT.

Likewise, this class provides various ways to operate on instants. For example:

Parsing and Formatting

Formating

The JDK provides a new API to parse and format Temporal-based objects, using the from the package we can parse and format dates and times. Similar to most other new Date/Time API classes, is immutable thus thread-safe.

The method is provided by those classes for formatting temporal-based objects for display. For example, this snippet of code format date and time using a predefined formatter:

We can also define a custom formatter object using method:

Make sure to take a look at the reference documentation if you want to know more about the syntax used in the method argument.

Parsing

Now you know how to convert Temporal-based classes into strings, let’s see how we can convert into the other direction using the method:

returns a by parsing the text string using a custom formatter object. While parses the text string and returns a using the default formatter (DateTimeFormatter.ISO_LOCAL_TIME)

A Peek on Dates and Times Before Java 8

Before Java 8, developers used the class, which represents the date and time altogether. There was no way to get a date or time separately, and it was all bundled in the class. Developers should not use this class anymore, as you’ve seen, there is a better way. This class exists to support backward compatibility.

Another disadvantage of the class is that it’s mutable. Therefore, you need to synchronize access to instances of this class when they’re accessed from multiple threads to avoid data corruption and unexpected behavior.

You may encounter the old Date API in legacy projects. You create a date by calling its constructor: , refers to the current date/time. You can specify a specific date using the class:

You can see how much verbose this old API compared to the new one. Beware that Month indexes are zero-based instead of one-based, which is confusing. The new API’s indexes are one-based.

Wrap Up

In this post, I attempted to demonstrate why you should work with the new Date/Time API, how to work with it, how to format and parse dates and times. And, peeked at how dates/times were handled before Java 8.

If you found this post useful, you know what to do now. Hit that clap button and follow me to get more articles and tutorials on your feed.

Hamza(@HamzaLovesJava) is a self-taught developer and Java enthusiast. In his free time, he likes to blog about various technical topics at https://hamza-jvm.me