Java 8 - ZonedDateTime example




The java.time.ZonedDateTime class is an immutable class which represents a date-time with time-zone information such as ‘2017-06-16T21:25:37.258+05:30[Asia/Calcutta]’.

The following examples are provided to demonstrate the usage of the ZonedDateTime in java program.

 

How to create a ZonedDateTime object in Java

You can use the ZonedDateTime.now() and ZonedDateTime.of() methods to create the current and specific date-time object with zone information as follows.

package com.boraji.tutorial.datetime;

import java.time.Clock;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class ZonedDateTimeExample {
   public static void main(String[] args) {
      // Current date time
      ZonedDateTime dateTime1 = ZonedDateTime.now();
      System.out.println(dateTime1);

      // Current date time from specified time-zone
      ZonedDateTime dateTime2 = ZonedDateTime.now(ZoneId.of("UTC"));
      System.out.println(dateTime2);

      // Current date time from specified clock
      ZonedDateTime dateTime3 = ZonedDateTime.now(Clock.systemDefaultZone());
      System.out.println(dateTime3);

      // Current zoned date time from LocalDateTime
      ZonedDateTime dateTime4 = ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("GMT"));
      System.out.println(dateTime4);

      // Specific zoned date time from LocalDateTime
      ZonedDateTime dateTime5 = ZonedDateTime.of(LocalDateTime.of(2017, 05, 12, 05, 45),
            ZoneId.of("Europe/London"));
      System.out.println(dateTime5);
   }
}

Output

2017-06-16T21:51:30.210+05:30[Asia/Calcutta]
2017-06-16T16:21:30.211Z[UTC]
2017-06-16T21:51:30.211+05:30[Asia/Calcutta]
2017-06-16T21:51:30.211Z[GMT]
2017-05-12T05:45+01:00[Europe/London]

 

How to get LocalDateTime, LocalDate, LocalTime, OffsetDateTime and Instant from ZonedDateTime

You can use the toXXXX() methods to get LocalDateTime, LocalDate, LocalTime, OffsetDateTime and Instant from ZonedDateTime.

package com.boraji.tutorial.datetime;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;

public class ZonedDateTimeExample {
   public static void main(String[] args) {
      // Current date time with zone
      ZonedDateTime dateTime = ZonedDateTime.now();
      System.out.println(dateTime);

      // Get LocalDateTime
      LocalDateTime localDateTime = dateTime.toLocalDateTime();
      System.out.println(localDateTime);

      // Get LocalDate
      LocalDate localDate = dateTime.toLocalDate();
      System.out.println(localDate);

      // Get LocalTime
      LocalTime localTime = dateTime.toLocalTime();
      System.out.println(localTime);

      // Get OffsetDateTime
      OffsetDateTime offsetDateTime = dateTime.toOffsetDateTime();
      System.out.println(offsetDateTime);

      // Get Instant
      Instant instant = dateTime.toInstant();
      System.out.println(instant);
   }
}

Output

2017-06-16T22:12:16.942+05:30[Asia/Calcutta]
2017-06-16T22:12:16.942
2017-06-16
22:12:16.942
2017-06-16T22:12:16.942+05:30
2017-06-16T16:42:16.942Z

 

How to get year, month, day from ZonedDateTime

You can use the getYear()getMonth()getDayOfMonth(), getZone() and getOffset() methods of the ZonedDateTime class to get year, month and day etc.

package com.boraji.tutorial.datetime;

import java.time.ZonedDateTime;

public class ZonedDateTimeExample {
   public static void main(String[] args) {

      ZonedDateTime dateTime = ZonedDateTime.now();

      System.out.println("Year : " + dateTime.getYear());
      System.out.println("Month : " + dateTime.getMonth().getValue());
      System.out.println("Day of Month : " + dateTime.getDayOfMonth());
      System.out.println("Day of Week : " + dateTime.getDayOfWeek());
      System.out.println("Day of Year : " + dateTime.getDayOfYear());
      System.out.println("Zone Id : " + dateTime.getZone());
      System.out.println("Offset : " + dateTime.getOffset());
   }
}

Output

Year : 2017
Month : 6
Day of Month : 16
Day of Week : FRIDAY
Day of Year : 167
Zone Id : Asia/Calcutta
Offset : +05:30

 

How to get Hour, Minute, Second from ZonedDateTime

You can use the getHour()getMinute() and getSecond() methods of the ZonedDateTime class to get hour, minute and second respectively.

package com.boraji.tutorial.datetime;

import java.time.ZonedDateTime;

public class ZonedDateTimeExample {
   public static void main(String[] args) {

      ZonedDateTime dateTime = ZonedDateTime.now();

      System.out.println("Hour : " + dateTime.getHour());
      System.out.println("Minute : " + dateTime.getMinute());
      System.out.println("Second : " + dateTime.getSecond());
      System.out.println("Nano : "+dateTime.getNano());
   }
}

Output

Hour : 22
Minute : 44
Second : 5
Nano : 107000000

 

How to add or subtract years, months, days, hours, minutes and seconds to ZonedDateTime

You can use the plus and minus methods of the ZonedDateTime class to add or subtract days, months, hours, minutes etc.

package com.boraji.tutorial.datetime;

import java.time.ZoneId;
import java.time.ZonedDateTime;

public class ZonedDateTimeExample {
   public static void main(String[] args) {

      ZonedDateTime dateTime = ZonedDateTime.now(ZoneId.of("America/New_York"));

   // LocalDateTime's plus methods 
      System.out.println("Addition of days : " + dateTime.plusDays(5));
      System.out.println("Addition of months : " + dateTime.plusMonths(15));
      System.out.println("Addition of years : " + dateTime.plusYears(5));
      System.out.println("Addition of Hours : " + dateTime.plusHours(2));
      System.out.println("Addition of Minutes : " + dateTime.plusMinutes(30));
      System.out.println("Addition of Seconds : " + dateTime.plusSeconds(20));

      // LocalDateTime's minus methods 
      System.out.println("Subtraction of days : " + dateTime.minusDays(5));
      System.out.println("Subtraction of months : " + dateTime.minusMonths(15));
      System.out.println("Subtraction of years : " + dateTime.minusYears(5));
      System.out.println("Subtraction of Hours : " + dateTime.minusHours(2));
      System.out.println("Subtraction of Minutes : " + dateTime.minusMinutes(30));
      System.out.println("Subtraction of Seconds : " + dateTime.minusSeconds(20));
   }
}

Output

Addition of days : 2017-06-21T13:17:15.558-04:00[America/New_York]
Addition of months : 2018-09-16T13:17:15.558-04:00[America/New_York]
Addition of years : 2022-06-16T13:17:15.558-04:00[America/New_York]
Addition of Hours : 2017-06-16T15:17:15.558-04:00[America/New_York]
Addition of Minutes : 2017-06-16T13:47:15.558-04:00[America/New_York]
Addition of Seconds : 2017-06-16T13:17:35.558-04:00[America/New_York]
Subtraction of days : 2017-06-11T13:17:15.558-04:00[America/New_York]
Subtraction of months : 2016-03-16T13:17:15.558-04:00[America/New_York]
Subtraction of years : 2012-06-16T13:17:15.558-04:00[America/New_York]
Subtraction of Hours : 2017-06-16T11:17:15.558-04:00[America/New_York]
Subtraction of Minutes : 2017-06-16T12:47:15.558-04:00[America/New_York]
Subtraction of Seconds : 2017-06-16T13:16:55.558-04:00[America/New_York]

 

How to compare ZonedDateTime objects in Java

You can use the isEqual()compareTo()isAfter() and isBefore() methods of the ZonedDateTime class to compare the ZonedDateTime objects.

package com.boraji.tutorial.datetime;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class ZonedDateTimeExample {
   public static void main(String[] args) {

      LocalDateTime dateTime = LocalDateTime.now();

      ZonedDateTime dt1 = ZonedDateTime.of(dateTime, ZoneId.of("America/New_York"));
      ZonedDateTime dt2 = ZonedDateTime.of(dateTime, ZoneId.of("America/New_York"));
      ZonedDateTime dt3 = ZonedDateTime.of(dateTime, ZoneId.of("UTC"));

      // Using isEqual()
      if (dt1.isEqual(dt2)) {
         System.out.println("dateTime1 and dateTime2 are equal.");
      } else {
         System.out.println("dateTime1 and dateTime2 are not equal.");
      }

      // Using compareTo()
      if (dt1.compareTo(dt2) == 0) {
         System.out.println("dateTime1 and dateTime2 are equal.");
      } else {
         System.out.println("dateTime1 and dateTime2 are not equal.");
      }

      // Using isAfter()
      if (dt2.isAfter(dt3)) {
         System.out.println("dateTime2 is after dateTime3");
      }

      // Using isBefore()
      if (dt3.isBefore(dt1)) {
         System.out.println("dateTime3 is before dateTime1");
      }
   }
}

Output

dateTime1 and dateTime2 are equal.
dateTime1 and dateTime2 are equal.
dateTime2 is after dateTime3
dateTime3 is before dateTime1

 

How to get number of days in a month or year using ZonedDateTime

First, convert the ZonedDateTime to LocalDate then use lengthOfMonth() and lengthOfYear() methods of the LocalDate class to count the number of days in a month and year respectively.

package com.boraji.tutorial.datetime;

import java.time.LocalDate;
import java.time.ZonedDateTime;

public class ZonedDateTimeExample {
   public static void main(String[] args) {
      ZonedDateTime dateTime = ZonedDateTime.now();

      // Get LocalDate from ZonedDateTime
      LocalDate localDate=dateTime.toLocalDate();
      if (localDate.isLeapYear()) {
         System.out.println(localDate.getYear() + " is a leap year");
      } else {
         System.out.println(localDate.getYear() + " is not a leap year");
      }
   }
}

Output 

2017 is not a leap year

 

How to convert or parse String to ZonedDateTime in java

You can use the parse() method of the ZonedDateTime class to convert the String to ZonedDateTime.

package com.boraji.tutorial.datetime;

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class LocalTimeExample {
   public static void main(String[] args) {

      // ISO date time
      ZonedDateTime dt1 = ZonedDateTime.parse(
            "2017-03-28T12:25:38.492+05:30[Asia/Calcutta]",
            DateTimeFormatter.ISO_ZONED_DATE_TIME);
      System.out.println(dt1);

      // 'yyyy-MMM-dd HH:mm:ss' pattern
      ZonedDateTime dt2 = ZonedDateTime.parse("2017-May-02 23:35:05", DateTimeFormatter
            .ofPattern("yyyy-MMM-dd HH:mm:ss").withZone(ZoneId.of("UTC")));
      System.out.println(dt2);

      // 'yyyy-MM-dd KK:mm:ss a' pattern
      ZonedDateTime dt3 = ZonedDateTime.parse("2017-05-30 10:20:30 AM", DateTimeFormatter
            .ofPattern("yyyy-MM-dd KK:mm:ss a").withZone(ZoneId.systemDefault()));
      System.out.println(dt3);

      // 'cccc, MMMM dd, yyyy KK:mm a' pattern
      ZonedDateTime dt4 = ZonedDateTime.parse("Wednesday, May 31, 2017 10:21 PM",
            DateTimeFormatter.ofPattern("cccc, MMMM dd, yyyy KK:mm a")
                  .withZone(ZoneId.of("Europe/Paris")));
      System.out.println(dt4);
   }
}

Output

2017-03-28T12:25:38.492+05:30[Asia/Calcutta]
2017-05-02T23:35:05Z[UTC]
2017-05-30T10:20:30+05:30[Asia/Calcutta]
2017-05-31T22:21+02:00[Europe/Paris]

 

How to convert or format ZonedDateTime to String in java

You can use the format() method of the ZonedDateTime class to convert the ZonedDateTime to String.

package com.boraji.tutorial.datetime;

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class LocalTimeExample {
   public static void main(String[] args) {

      // ISO pattern
      ZonedDateTime dateTime = ZonedDateTime.now();
      System.out.println(dateTime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));

      // 'yyyy-MMM-dd HH:mm:ss z' pattern
      System.out.println(
            dateTime.format(DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss z")));

      // 'yyyy-MM-dd KK:mm:ss a' pattern
      System.out.println(
            dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd KK:mm:ss a")));

      // 'cccc, MMMM dd, yyyy KK:mm a' pattern
      System.out.println(
            dateTime.format(DateTimeFormatter.ofPattern("cccc, MMMM dd, yyyy KK:mm a")));
   }
}

Output

2017-06-18T09:17:58.676+05:30[Asia/Calcutta]
2017-Jun-18 09:17:58 IST
2017-06-18 09:17:58 AM
Sunday, June 18, 2017 09:17 AM

 

How to get ZonedDateTime from LocalDateTime, OffsetDateTime and Instant

The following example demonstrates how to get the ZonedDateTime time from the LocalDateTime, OffsetDateTime and Instant.

package com.boraji.tutorial.datetime;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class LocalTimeExample {
   public static void main(String[] args) {

      LocalDateTime localDateTime = LocalDateTime.now();
      ZonedDateTime dateTime1 = localDateTime.atZone(ZoneId.systemDefault());
      System.out.println(dateTime1);

      OffsetDateTime offsetDateTime = OffsetDateTime.now();
      ZonedDateTime dateTime2 = offsetDateTime.atZoneSameInstant(ZoneId.of("Europe/London"));
      System.out.println(dateTime2);

      Instant instant = Instant.now();
      ZonedDateTime dateTime3 = instant.atZone(ZoneId.of("US/Pacific"));
      System.out.println(dateTime3);
   }
}

Output

2017-06-18T09:33:08.515+05:30[Asia/Calcutta]
2017-06-18T05:03:08.531+01:00[Europe/London]
2017-06-17T21:03:08.531-07:00[US/Pacific]