Date and Time APIs in Java

Photo by Jon Tyson on Unsplash

“Time is the wisest counselor of all.” — Pericles

When dealing with software it is important to keep track of the right date and time, in domains like fintech and medical this is a critical element. When developing applications developers always tend to focus on the business problem when developing the application without re-inventing the wheel.

In Java to deal with these Date and Time problems to the precious, it has few prebuilt libraries we can use before Java 8, those are,

  • java.util.Date
  • java.util.Calendar
  • java.text.SimpleDateFormat
  • java.util.TimeZone

Those two legacy API came with few issues,

  1. Date class should represent a date but it also represents the minutes hours and seconds as well. as an example
Date now = new Date();

And if looks closely Date does not have an associated time zone it picks up the default timezone of the server/pc it is running. This would be an issue if users are residing somewhere else geographically but the server is hosted in another time zone.

2. The classes used a zero index-based approach to represents the months, this might make confusions some times

Calendar calendar = Calendar.getInstance();
System.out.println(calendar.JANUARY);

3. And another class which used in dealing with the Date has a time zone since this is used in JDBC and getting data back from the database and convert to Java Date format causing issues.

To deal with those issues and fix them from Java 8, it came with the new set of API for Date and Time those are,

  • java.time.LocalDate — This represents only the time according to the ISO calendar.
  • java.time.LocalTime — This represents only the time in a human-readable manner.
  • java.time.LocalDateTime — Both the Date and Time without having a time zone will be handled here. This is a combination of LocalDate and LocalTime.
  • java.time.ZonedDateTime LocalDateTime combines with the time zone provided using ZoneId class.
  • java.time.OffsetTime — Handles time with a corresponding time zone offset from Greenwich/UTC, without a time zone ID.
  • java.time.OffsetDateTime — Handles a date and time with a corresponding time zone offset from Greenwich/UTC, without a time zone ID.
  • java.time.Clock — Provides access to the current instant, date, and time in any given time zone.
  • java.time.Instant — represents the start of a nanosecond on the timeline and useful for generating a timestamp to represent machine time
  • java.time.Duration — Difference between two instants and measured in seconds or nanoseconds and does not use date-based constructs such as years, months, and days, though the class provides methods that convert to days, hours, and minutes.
  • java.time.Period — To define the difference between dates in date-based values (years, months, days).
  • java.time.ZoneId — specifies a time zone identifier and provides rules for converting between an Instant and a LocalDateTime.
  • java.time.ZoneOffset — Specifies a time zone offset from Greenwich/UTC.

Let’s find out how each one of these works practically. There are few ways we can initialize Date and Time objects.

The output will be somewhat like this(Value depended on the date and time running)

Today : 2021-05-04
This time : 14:52:23.764490100
Current Time : 2021-05-04T14:52:23.764490100
Someday : 2020-06-12
Sometime : 23:53
Other Date Time : 2021-03-04T10:51:44

Extracting and Combining Date, Time Values

Sometimes there are requirements to get only the date or time from the LocalDaeTime or combine date or time into the existing value, there are few ready-made functions we can use functions such as “toLocalDate(), toLocalTime()” to extract. also If there is only a portion is needed from a date-time, this can be Month or Year then it can be extracted using “getX()” this can be getYear(), getMonth(), getHour() methods.
And “atTime(LocalTime), atDate(LocalDate), to combine. Here is an example below.

the output will result like this,

Someday : 2020-03-19
Sometime : 23:53
2020-03-19T23:53
2020-03-19T23:53
2020-03-19
23:53

Operations in Date Time API

LocalDateTime, LocalDate, LocalTime objects are immutable objects, so we cannot apply operators, But it is necessary to add, subtract, ranges, and calculations for date and time, Java has provided operations for the objects.
As an example, if we want to add we can use plusX(), if substracting minusX(), this “X” can be replaced with “Years, Months, Hours, Days”.

Furthermore, when it comes to comparing there are methods like “isBefore()” or “isAfter()” to check against another date, here’s an example below

Instants, Durations, and Periods in Java

When dealing with the Times and dates, it is not the only thing required to use the date and times we might need to express the amount of time for these scenarios has brought some classes like

  • java.time.Duration — class to represent the time in nanoseconds.
  • java.time.Period — used to express the time in units such as year, including the distance between two times or days, mostly used to write business functions.
  • java.time.Instant — used to represent the instance of a time(timestamp), and better to use in logging APIs & system tasks.

Similar to the LocalDate and LocalDateTime there are similar methods to carry out the operations such as now(), ofX(), plusX(), minusX(), withX(), and getX(). and functions like between() and isNegative() for handle distance between the point of time. Let’s look at the example below.

In the example above what it does is that it get the current date, and calculate how much time left for the Christmas day using the “Period” class provided by Java. and finally, we extract how many years, months, and date as single elements. Output is somewhat like this to the Date of May 04, 2021

Current Date : 2021-May-04
Years : 0
Months : 7
Days : 21

Now let’s look at how we can use Instant and Duration provided by the Java 8+

Using the instant we can retrieve the current timestamp this includes the current date time and the nanoseconds, Also the timestamp provides “getNano()” to extract only the nanoseconds from the last second at the timestamp recorded.
Using the Duration we can set a certain period of time using “ofHours()”, “ofDays()” and apply the arithmetic operations also. and converting them back to the appropriate values such as seconds, minutes as needed.

Daylight Saving and Dealing with Different Time Zones

Most of the time applications are not limited to the users in one geographical area with the same time zones at that time there should be a mechanism to handle date and time according to how it fits with other parts of the world. Java has a special class provided for this which is java.time.ZonedDateTime

ZoneDateTime class consists of the same capabilities in the LocalDateTime class but it provides the date and time values according to the time zone rules, this includes daylight saving issue to deal with the “withZoneSameInstant()” function. But to define the time zone there should be the help of another class which is the java.time.ZoneId class. There are few ways we can initialize a ZoneId

ZoneId zurich = ZoneId.of("Europe/Zurich");
ZoneId rome = ZoneId.of("GMT+2");
ZoneId seattle = ZoneId.of("UTC-7");

Let’s look at the code from a detailed perspective to view how to get things together. Let’s first take a scenario we have a past date-time, We want to know what was the time at a different time zone at that time

In the above example what it does is first initializes a time, and then create two time zones, Berlin, and Denver, USA. We map the defined date with Berlin’s time zone, Which means we tell the program that this is the time and date in Berlin in the 18th line.

And using the “withZonedSameInstant()” it finds what was the date and time in Denver, when it was in 2021 February 21st at 6.30 PM Java ZonedDateTime will solve this for us and it returns the output like this.

2021-02-20T18:30+01:00[Europe/Berlin]
2021-02-20T11:30-06:00[GMT-06:00]

Now Let’s find the current Date and Time based on our region.

In the above program what it does is get the current time and the current zone which your pc/server set into and map that both date, time with the time zone, based on our time it calculates the current time of few other cities in different time zones. If we can extract only the date or time it is also possible by the “toLocalDate()” or toLocalTime()

Formatting & Parsing Date and Time

It is not only enough to represent the date and time in different time zones but there might be a need of representing them in a standard way according to the time zone.

For the standard way of formatting first, the application should be adjustable to represent in local language and format, java.util.Locale is the class supported in the Java environment to represent the languages and countries.

After setting the Locale to format the time into the local format Java comes with the java.time.format.DateTimeFormatter, which provides the ability to present the date-time value as a standard way or preferable custom way.

Let’s look at an example of formatting the Date and Times according to different countries and languages.

In the above code, what it does is as the first step, it will set Locale to few countries with different date formats and languages, and it will use DateTimeFormatter to set how the different date format should display manually and also automatically according to locale. Lastly, format the given date and assign it to a String object for representation.
And the output is like this (at May 06, 2021),

Thursday May 06 2021
2021 මැයි 6
木曜日 2021 06 5月
06.05.2021

Software Engineer