ZonedDateTime In Java 8

There are different TimeZones all over the earth. Java has been implementing all the zones over these TimeZones and it uses Internet Assigned Numbers Authority  (IANA) database

The zones are available from a class called ZoneId. I can get the set of all zones by below code.

If I need to have the special time zone, I just need to pass the name of that time zone as a parameter to of static method, It will bring up the UK time zone.

Ways to Create a ZonedDateTime Class Object:

There are couples of ways to create ZonedDateTime object. The first way is to call the now() method of the ZonedDateTime class. Here is an example of creating a ZonedDateTime object using the now() method:

Another way to create a ZonedDateTime object is to use the of() method which can create a ZonedDateTimeobject from a concrete date and time. Here is an example of creating a ZonedDateTime object using the of() method by passing Year, Month , Day, Hours, Minute, Seconds, Nanos and passing Zone Id of this time.

So here we are creating point on the time line in the zone id Europe/London which is United Kingdom.

Date and Time Calculations Using ZonedDateTime Class

ZonedDateTime class exposes a set of methods to compute other zoned times plus, minus,with etc.

Lets suppose I have to create first meeting on date 12th march 2014 at 9.30AM with zone id Europe/London.

Then I want scheduled my next meeting one months later. I just to need a Period a one month to our current meeting.

And if this meeting also involved the people from the other time zone let suppose from US. So I want to invite them for this meeting too with their proper time in there time zone. So I will convert nextMeeting  zonedDateTime inside there time zone by calling withZoneSameInstant() method, so It will be the same Instant of the timeline, off course if it’s not we have problem to meet. But it is not the same hours as the time zones are not the same. So I called withZoneSameInstant() method and passing it the zone id of US/Central for our example

Also see next tutorial, how we can format this ZoneDateTime object using DateTimeFormatter class available in  java.time.format.DateTimeFormatter package, introduced in Java 8.


Leave a Reply

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