Date, Time and TimeZone in Java

Bavatharany Mahathevan
8 min readDec 16, 2021

Working with date and time is really a challenging task in programming and the most important task too obviously. We should pay more attention to the Date and Time when we develop applications for maintaining the data effectively. In this article, Let's go through how java handles the Date and Time with Timezone and how we as developers are going to use it sensitively.

Before going to the serious thing, let's look at the fact history of our time and calendar system.

In our Srilanka, as you know, the time was calculated based on the sunrise and our ancients were able to calculate current time by just looking at the place of sun and direction. Likewise, all countries calculated their time on a different basis earlier. However, it was not possible for global.

In the 18th century, people faced this time difference issue between countries when they had been travelling from one country to another country by train. Therefore they decided to bring a standers time, As a result, the Greenwich association introduced a standard time formula named GMT means Greenwich Mean Time. So that, they calculated the time format based on zero degrees of longitude for all countries. This is the first step to determine the time zone of other countries in regard to GMT+0. Therefore, the difference in time for other countries is indicated either by adding or subtracting hours from GMT time.

Even though the GMT was not a uniform time in the more global work. Then, the concept UTC was introduced as a standard time and GMT is used as a timezone.

Before discussing UTC, let's see the next interesting history.

September 1752 calendar missing 11 days.

Here, I have attached the story. You can refer to the below link to understand the story deeply.

https://lifeinsaudiarabia.net/why-are-11-days-missing-in-calendar-of/

What is UTC?

Coordinated Universal Time is the global time standard by which the world regulates clocks and time. It is within about 1 second of mean solar time at zero degrees longitude and is not adjusted for daylight saving time.

What is DST?

Daylight Saving Time is the practice of setting the clocks forward one hour from standard time during the summer months, and back again in the fall, in order to make better use of natural daylight.

So that, the clock forward one hour on the Second Sunday of March, and set back one hour on the First Sunday in November. As a result, summer month has a day that with 25 hours and autumn month has a day that with 23 hours.

Srilanka, India, China and Japan are the countries that do not observe some form of daylight saving.

Next. let's go with Java APIs.

Before Java 8, There were APIs for handling the date and time in programming such as Date, Calander and TimeZone in java.util* package. Java 8 introduced new APIs to cover the issues in old APIs.

what are the issues in older API?

  1. Inconvenient API design : The Date and Calendar APIs are poorly designed with inadequate methods to perform day-to-day operations. example : the date class has both time and date components., If you want to work with only time information, you must set zero value for the date.
  2. Not thread safety : Date and Calendar classes are not thread-safe. So there are some concurrency issues.
  3. ZonedDate and Time : Developers have to handle the timezone logic additionally.

Java 8 provides more support for the date and Time functionalities with the classes like LocalDate, LocalTime, LocalDateTime, Instant, Period, Duration and TemporalUnit in java.time package.

Let's see one by one.

LocalDate class

  • java.time.LocalDate
  • It represents only a date without time or time zone.
  • LocalDate class is represented in theISO-8601 calendar system in a year-month-day format YYYY-MM-DD
  • So that, the order is a year, month, date respectively.
  • Example: 2021–12–16
  • If we interchange the order, then we will get the java.time.DateTimeException
LocalDate today = LocalDate.now();System.out.println("Today's date is: " + today)

The above LocalDate.now() will print the current date from the system clock in the default time zone. The out will be Today’s date is: 2021–12–16

The now() method is overloaded. Let's look at the below image.

now() method is overloaded.

Let's see another example.

The overloaded of() method can be used to get the Date object with the specified year, month and date.

LocalDate newYear2022 = LocalDate.of(2022, 1, 1);System.out.println("New year 2022: " + newYear2022);

The above LocalDate.of(2022, 1, 1); will print the following result

New year 2022: 2021–01–01

To avoid the confusion with the date and month parameter of the LocalDate.of the () method, we can use the improved version like

LocalDate NewYear = LocalDate.of(2022, Month.April, 14);System.out.println(“The new year is: “ + NewYear);

It will print the following result :

The new year is: 2022–04–14

Likewise, The class Localdate has many methods to provide the functionalities with Date.

LocalTime Class

  • The java.time.LocalTime
  • LocalTime represents time without dates or time zones.
  • The time is in the ISO-8601 calendar system format: HH:MM:SS.nanosecond
  • Both LocalTime and LocalDate use the system clock and the default time zone.
LocalTime currentTime = LocalTime.now();System.out.println("The current time is: " + currentTime);

Like locaDate.now() , the above now() method will print the currentTime

The current time is: 19:49:08.400601600

As the same LocalDate, The overloaded of() method provides different Time objects.

Let's see an example.

LocalTime myTime = LocalTime.of(19,56);System.out.println("myTime difined time is: " + myTime);

The above code will print as my defined time is : 19:56 always.

The below image shows the overloaded of() method, we can develop our system with them effectively.

LocalDateTime Class

  • java.time.localDateTime
  • It represents both the Date and Time combination without a time zone.
  • ISO-8601 format is YYYY-MM-DD HH:MM: SS.nonoseconds.
LocalDateTime currentDateTime = LocalDateTime.now();System.out.println("current date and time is : " + currentDateTime);

The above code will print the current date and time :

current date and time is : 2021–12–16T20:19:32.294928900

did you notice it, there is a T in the output?

The T stands for time, it separates the date and time.

The toLocalDate(),toLocalTiem() methods are used to get Date and Time objects from the LocalDateTime object respectively from the LocalDateTiem object.

Let's see the below example.

LocalDateTime dateTime = LocalDateTime.now();System.out.println("Today's date and current time: " + dateTime);System.out.println("The date is: " + dateTime.toLocalDate());System.out.println("The time is: " + dateTime.toLocalTime());

The above code will print the output like:

Today’s date and current time: 2021–12–16T20:32:09.412505400

The date component is: 2021–12–16

The time component is: 20:32:09.412505400

Dealing with Timezones and Daylight saving

The discussed classes LocalDate, LocalTime and LocalDateTime work without timezone. Now, let's see, how to work with Date and Time across time zones, deal with daylight savings.

Like the above three classes, here, there are another three classes for working with timezone.

  1. ZoneId
  2. ZonedOffSet
  3. ZonedDateTime class

ZoneId class

  • java.time.zoneId
  • It represents the zone id of a country.
  • We can return our zone id passing the argument time zone
  • The time zone actually is provided with the city/region of a country.

let's see the below example.

ZoneId myTimezone = ZoneId.systemDefault();System.out.println("My time zone  is: " + myTimezone );

The above code will print like :

My time zone is: Asia/Colombo

For Sri Lanka, the time zone is Asia/Colombo

ZoneId.getAvailableZoneIds() will return list of tiemzone for all counties.

You can pass any of these time-zone identifiers to the of() method to create the corresponding ZoneId object

ZoneId colomboZoneId = ZoneId.of(“Asia/Colombo”);

ZoneOffset class

ZoneId identifies a time zone, such as Asia/Colombo. while ZoneOffset represents the time-zone offset from UTC/Greenwich.

Example: Srilanka time zone is Asia/Colombo and time zone offset is +5.30.it means our country time at a point UTC+ 5 hour 30 minutes.

When UTC time is 4.10 am, SriLanka time is 9.40 am

ZonedDateTime class

  • java.time.ZonedDateTime class.
  • ZonedDateTime is a combination of Date, Time and TimeZone.
  • Let look at the below example, how we can work with timezone.
LocalDate currentDate = LocalDate.now();LocalTime currentTime = LocalTime.now();ZoneId myZone = ZoneId.systemDefault();ZonedDateTime zonedDateTime = ZonedDateTime.of(currentDate, currentTime, myZone);System.out.println(zonedDateTime);

The code will print :

2021–12–17T10:05:19.689872100+05:30[Asia/Colombo]

The below code snippet and its output illustrate the purpose of each class and the differences between them. I hope it helps you to understand them.

//Asia/Colombo
ZoneId myZone =ZoneId.of("Asia/Colombo");
System.out.println(myZone);
//dateTime : 2021–12–17T10:13:39.715259500
LocalDateTime dateTime = LocalDateTime.now();
System.out.println("dateTime : "+ dateTime);
//2021–12–17T10:13:39.715259500+05:30[Asia/Colombo]
ZonedDateTime zonedDateTime = dateTime.atZone(myZone);
System.out.println(zonedDateTime);
//+05:30
ZoneOffset zoneOffset = zonedDateTime.getOffset();
System.out.println(zoneOffset);

output :

  • Asia/Colombo
  • dateTime : 2021–12–17T10:13:39.715259500
  • 2021–12–17T10:13:39.715259500+05:30[Asia/Colombo]
  • +05:30

Dealing with Daylight Saving.

As we already discuss the dayLight saving, There is more daylight in summer periods and less daylight in fall periods. The class ZonedDateTime handles the DST itself.

Let's see the below code snippet for understanding more.

ZoneId AustraliaZone = ZoneId.of("Australia/Sydney");Duration SydneyDST = AustraliaZone.getRules().getDaylightSavings(Instant.now());System.out.println("Sydney zone DST is: "+ SydneyDST.toHours());ZoneId New_YorkZone = ZoneId.of("America/New_York");Duration New_YorkDST = New_YorkZone.getRules().getDaylightSavings(Instant.now());System.out.println("New_York zone DST is: "+ New_YorkDST.toHours());

output :

Sydney zone DST is: 1

New_York zone DST is: 0

Today -December, Austalia’s DST is 1 in the summer period. It means that Australia's time is different from Srilanka in winner 4 hours and 30 minutes and in summer the difference is 5 hours and 30 minutes.

  • zoneId.getRules().getDaylightSavings(Instant.now()) returns a Duration object based on whether DST is in effect at that time.
  • zonedDateTime.getOffset() returns a ZoneOffset object that corresponds to the offset of the time zone from UtC/greenwich.

As we work with UTC, people who are in another zone also can have their operations with their time zone without any conflict.

java.sql.Date

The java.sql.Date class represents the only date in Java. It is mostly used in the JDBC to store in a database.

Let's see the code snippet and the default date format in Java.sql.Date API.

long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
System.out.println("sql date is " + date);

The out is SQL date is 2021–12–23, while I am writing this blog.

And the Date class of the java.sql API has methods for handling the date and time efficiently such as converting string to date, to set date, changing the Data to Instance and LocalDate type.

Epoch time

  • It is known as Epoch Unix Time.
  • Actually, Epoch time is the total seconds we passed at this movement from 1970 January 1 UTC time.
  • The total number of seconds for a day is 24* 60*60 seconds.
  • Epoch time return the long number between the current time and 1 January 1970
  • Java 8, Date and Time APIs also support getting the epoch time with a deal of date, time and time zone.
  • let's see the below code snippet to get Epoch time for the current time. It is easy to get the current time in Epoch time in java
long epochTimewithJava8 = Instant.now().getEpochSecond();System.out.println(epochTimewithJava8); // 2021/12/22 23.45

The out 1640196974 is total seconds have been passed since 1st January 1970 , while I am writing this blog. Here, the Instant class.

You can refer to more details and convert epoch time in all programming languages https://www.analyticsvidhya.com/blog/2021/05/making-programming-with-date-and-time-less-painless/

--

--