ZonedDateTime format example in Java 8

ZonedDateTime format example in Java 8

ZonedDateTime class in Java 8 is an immutable representation of a date-time with a time-zone. It is equivalent of GregorianCalendar class present in versions prior to Java 8. By using this class, you can convert local time to equivalent time in another time zone. Since it is immutable, all methods performing calculations on a ZonedDateTime object returns a new ZonedDateTime instance. In this post we will see examples of using ZonedDateTime format in Java 8.

Creating a ZonedDateTime Object

There are a several ways to create a ZonedDateTime object.

#1) Using now() method.

ZonedDateTime zonedDateTime = ZonedDateTime.now();

The above line creates a ZonedDateTime object with the current date-time from the system clock in the default time-zone. It uses Java default time-zone, as per TimeZone.getDefault() method.

ZonedDateTime zonedDateTime = ZonedDateTime.now( ZoneId.of (“PST”));

The above line explicitly specifies the time-zone of America/Los_Angeles using ZoneId.

#2) Another way to create a ZonedDateTime object is by using the of() method. Here is an example.

#3) ZonedDateTime object can also be created using parse() method. Here is an example program.

Date and Time Calculations

The ZonedDateTime class provides a number of methods that can be used for date time calculations.

Here is an example program using some of the methods.

Below is the output of above program.

Note that calculations that span across the daylight savings changes (start or end) may not give the expected result. In that case we can use a Period instance as shown in below program.

Accessing Date and Time of a ZonedDateTime

You can access the date and time information of a ZonedDateTime object using one of the following methods

  • getYear()
  • getMonth()
  • getMonthValue()
  • getDayOfMonth()
  • getDayOfWeek()
  • getDayOfYear()
  • getHour()
  • getMinute()
  • getSecond()
  • getNano()

Here is an example program using some of the above methods.

Here is a sample output of the program.

That’s all about the usage of ZonedDateTime class in Java 8. If you have any doubts, post it in the comments section.

Also Read,

Date and calendar functions in Java

Joda Time library in Java

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.

Add Comment

Required fields are marked *. Your email address will not be published.