Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Monday, November 30, 2020

Java 8 ZonedDateTime Examples

1. Overview

In this article, We'll learn what is ZonedDateTime class and how to use effectively Dates with timezones in java 8.

ZonedDateTime class also an immutable class similar to the other date time api classes in java 8 and above and every method in this class will result in a new instance for this class with copy of every value.

ZonedDateTime class represents the date and time with the time zone values. This class stores the date and time fields and precision to the nano seconds along with the time zone value (with zone offset value to avoid ambiguous situation in local date times).

Java 8 ZonedDateTime Examples



2.  Java 8 ZonedDateTime Class Methods


Next, let use see the commonly used methods from the ZonedDateTime class.

static ZonedDateTime now(): It is used to obtain the current date-time from the system clock in the default time-zone.

String format(DateTimeFormatter formatter): It is used to format this date-time using the specified formatter.

int get(TemporalField field): It is used to get the value of the specified field from this date-time as an int.

ZoneId getZone(): It is used to get the time-zone, such as 'Asia/Kolkata'.

ZonedDateTime withZoneSameInstant(ZoneId zone): It is used to return a copy of this date-time with a different time-zone, retaining the instant.

static ZonedDateTime of(LocalDate date, LocalTime time, ZoneId zone): It is used to obtain an instance of ZonedDateTime from a local date and time.

ZonedDateTime minus(long amountToSubtract, TemporalUnit unit): It is used to return a copy of this date-time with the specified amount subtracted.

ZonedDateTime plus(long amountToAdd, TemporalUnit unit): It is used to return a copy of this date-time with the specified amount added.

int getDayOfYear(): It is used to get the day-of-year field.

int getHour(): It is used to get the hour-of-day field.

long getLong(TemporalField field): It is used to get  the value of the specified field from this date-time as a long.

int getMinute(): It is used to get  the minute-of-hour field.

Month getMonth(): It is used to get  the month-of-year field using the Month enum.

int getMonthValue(): Gets the month-of-year field from 1 to 12.

int getNano(): It is used to get  the nano-of-second field.

ZoneOffset getOffset(): It is used to get  the zone offset, such as '+01:00'.

int getSecond(): It is used to get  the second-of-minute field.

int getYear(): It is used to get  the year field.

ZoneId getZone(): It is used to get  the time-zone, such as 'Europe/Paris'.


3. Java ZonedDateTime Examples


Next, write a simple programs on the each method to understand clearly.

3.1 Creating ZonedDateTime Objects


Use now() or of() method to create the objects for the ZonedDateTime class. You can create the zoned date time from LocalDate, LocalTime or LocalDateTime objects using of() method.

package com.javaprogramto.java8.dates.zoneddatetime;

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

public class ZonedDateTimeCreateExample {

	public static void main(String[] args) {

		// Create ZonedDateTime Object - using current date and time from now()
		ZonedDateTime zonedDateTime = ZonedDateTime.now();
		System.out.println("ZonedDateTime current time value : " + zonedDateTime);

		// using of() method
		ZonedDateTime tokyoTime = ZonedDateTime.of(2025, 01, 01, 01, 01, 30, 1000, ZoneId.of("Asia/Tokyo"));
		System.out.println("Tokyo time : " + tokyoTime);

		// using of() method with localdate and localtime objects
		ZonedDateTime usaCentralTime = ZonedDateTime.of(LocalDate.now(), LocalTime.now(), ZoneId.of("America/Chicago"));
		System.out.println("chicago time : " + usaCentralTime);

		// using of() and LocalDateTime class
		ZonedDateTime estTime = ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("America/New_York"));
		System.out.println("new york time : " + estTime);
	}
}
 
Output:
ZonedDateTime current time value : 2020-11-30T13:47:32.985595+05:30[Asia/Kolkata]
Tokyo time : 2025-01-01T01:01:30.000001+09:00[Asia/Tokyo]
chicago time : 2020-11-30T13:47:32.986627-06:00[America/Chicago]
new york time : 2020-11-30T13:47:32.991812-05:00[America/New_York]

 

3.2 How to get the timezone from DateTime


Use getZone() method to get the time zone used by the ZonedDateTime object. We can also get the off set value from ZoneId.getRules() method.

package com.javaprogramto.java8.dates.zoneddatetime;

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

public class GetTimezoneExample {

	public static void main(String[] args) {
		// Create object using of() method
		ZonedDateTime zonedtime = ZonedDateTime.of(2023, 01, 01, 01, 01, 30, 1000, ZoneId.of("America/Chicago"));

		// Getting timezone in string
		ZoneId currentZoneId = zonedtime.getZone();

		// print the value onto console
		System.out.println("Get timezone : " + currentZoneId.getId());

		// printing the offset value
		System.out.println("Timezone offset value : " + currentZoneId.getRules());
	}
}
 
Output:
Get timezone : America/Chicago
Timezone offset value : ZoneRules[currentStandardOffset=-06:00]
 

3.3 Timezone Conversion Using ZonedDateTime


Let us convert one LocalDateTime value from IST to EST timezone.  Use withZoneSameInstant() method to convert date from one timezone to another.
package com.javaprogramto.java8.dates.zoneddatetime;

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

public class TimezoneConversionExample {

	public static void main(String[] args) {

		// Getting the current timezone.
		LocalDateTime localDateTime = LocalDateTime.now();

		// IST zone id
		ZoneId istZoneId = ZoneId.of("Asia/Kolkata");

		// Creating IST timezone datetime
		ZonedDateTime istTime = ZonedDateTime.of(localDateTime, istZoneId);

		// print ist time
		System.out.println("IST time : " + istTime);

		// creating est time zoneId.
		ZoneId estZoneId = ZoneId.of("America/New_York");
		
		// converting the ist time to est time using withZoneSameInstant() method
		ZonedDateTime estTime = istTime.withZoneSameInstant(estZoneId);
		
		// print est time
		System.out.println("EST time : "+estTime);
	}
}
 
Output:
IST time : 2020-11-30T14:51:10.184574+05:30[Asia/Kolkata]
EST time : 2020-11-30T04:21:10.184574-05:00[America/New_York]
 

3.4 Adding n Time Units to ZonedDateTime


Use plus() method add n no of a specific time units to the ZonedDateTime.
package com.javaprogramto.java8.dates.zoneddatetime;

import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;

public class ZonedDateTimePlusExample {

	public static void main(String[] args) {

		// Create ZonedDateTime Object - using current date and time from now()
		ZonedDateTime zonedDateTime = ZonedDateTime.now();
		System.out.println("ZonedDateTime current time value : " + zonedDateTime);

		// using plusXXX() method
		ZonedDateTime daysAdded = zonedDateTime.plusDays(10);
		ZonedDateTime hoursAdded = zonedDateTime.plusHours(10);
		ZonedDateTime monthsAdded = zonedDateTime.plusMonths(1);
		ZonedDateTime yearsAdded = zonedDateTime.plusYears(2);

		System.out.println("Days added : "+daysAdded);
		System.out.println("Hours added : "+hoursAdded);
		System.out.println("Months added : "+monthsAdded);
		System.out.println("yearss added : "+yearsAdded);
		
		// Using plus(timeunit, value)
		ZonedDateTime secondsAdded = zonedDateTime.plus(10, ChronoUnit.SECONDS);
		ZonedDateTime weeksAdded = zonedDateTime.plus(2, ChronoUnit.WEEKS);
		
		System.out.println("Seconds added : "+secondsAdded);
		System.out.println("Weeks added : "+weeksAdded);
	}

}
 
Output:
ZonedDateTime current time value : 2020-11-30T15:06:24.319161+05:30[Asia/Kolkata]
Days added : 2020-12-10T15:06:24.319161+05:30[Asia/Kolkata]
Hours added : 2020-12-01T01:06:24.319161+05:30[Asia/Kolkata]
Months added : 2020-12-30T15:06:24.319161+05:30[Asia/Kolkata]
yearss added : 2022-11-30T15:06:24.319161+05:30[Asia/Kolkata]
Seconds added : 2020-11-30T15:06:34.319161+05:30[Asia/Kolkata]
Weeks added : 2020-12-14T15:06:24.319161+05:30[Asia/Kolkata]

 

3.5 Subtracting n Time Units to ZonedDateTime


Use minus() method to go back to previous dates or time units. This method will subtract the time unit on the given date.
package com.javaprogramto.java8.dates.zoneddatetime;

import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;

public class ZonedDateTimeMinusExample {

	public static void main(String[] args) {

		// Create ZonedDateTime Object - using current date and time from now()
		ZonedDateTime zonedDateTime = ZonedDateTime.now();
		System.out.println("ZonedDateTime current time value : " + zonedDateTime);

		// using minusXXX() method
		ZonedDateTime daysSubtracted = zonedDateTime.minusDays(10);
		ZonedDateTime hoursSubtracted = zonedDateTime.minusHours(10);
		ZonedDateTime monthsSubtracted = zonedDateTime.minusMonths(1);
		ZonedDateTime yearsSubtracted = zonedDateTime.minusYears(2);

		System.out.println("Days Subtracted : "+daysSubtracted);
		System.out.println("Hours Subtracted : "+hoursSubtracted);
		System.out.println("Months Subtracted : "+monthsSubtracted);
		System.out.println("yearss Subtracted : "+yearsSubtracted);
		
		// Using minus(timeunit, value)
		ZonedDateTime secondsSubtracted = zonedDateTime.minus(10, ChronoUnit.SECONDS);
		ZonedDateTime weeksSubtracted = zonedDateTime.minus(2, ChronoUnit.WEEKS);
		
		System.out.println("Seconds Subtracted : "+secondsSubtracted);
		System.out.println("Weeks Subtracted : "+weeksSubtracted);
	}
}
 
Output:
ZonedDateTime current time value : 2020-11-30T16:57:08.648655+05:30[Asia/Kolkata]
Days Subtracted : 2020-11-20T16:57:08.648655+05:30[Asia/Kolkata]
Hours Subtracted : 2020-11-30T06:57:08.648655+05:30[Asia/Kolkata]
Months Subtracted : 2020-10-30T16:57:08.648655+05:30[Asia/Kolkata]
yearss Subtracted : 2018-11-30T16:57:08.648655+05:30[Asia/Kolkata]
Seconds Subtracted : 2020-11-30T16:56:58.648655+05:30[Asia/Kolkata]
Weeks Subtracted : 2020-11-16T16:57:08.648655+05:30[Asia/Kolkata]
 

3.6 Convert String to ZonedDateTime


Use ZonedDateTime.parse() method to convert string to ZonedDateTime in java.
package com.javaprogramto.java8.dates.zoneddatetime;

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

public class StringToZonedDateTimeExample {

	public static void main(String[] args) {

		// date in strig format
		String dateInString = "2020-11-16T16:57:08.648655+05:30[Asia/Kolkata]";

		// convert string to date format
		ZonedDateTime date = ZonedDateTime.parse(dateInString);

		// print the date onto console
		System.out.println("Final date created from string : " + date);

		// exception part.
		// trying into 
		String onlyDateInString = "2020-11-16";
		
		ZonedDateTime onlyDate = ZonedDateTime.parse(onlyDateInString, DateTimeFormatter.ISO_DATE);

		System.out.println("Only date" + onlyDate);
	}
}
 
Output:
Final date created from string : 2020-11-16T16:57:08.648655+05:30[Asia/Kolkata]
Exception in thread "main" java.time.format.DateTimeParseException: Text '2020-11-16' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 2020-11-16 of type java.time.format.Parsed
	at java.base/java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:2020)
	at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1955)
	at java.base/java.time.ZonedDateTime.parse(ZonedDateTime.java:598)
	at com.javaprogramto.java8.dates.zoneddatetime.StringToZonedDateTimeExample.main(StringToZonedDateTimeExample.java:23)
Caused by: java.time.DateTimeException: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 2020-11-16 of type java.time.format.Parsed
	at java.base/java.time.ZonedDateTime.from(ZonedDateTime.java:566)
	at java.base/java.time.format.Parsed.query(Parsed.java:235)
	at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1951)
	... 2 more
Caused by: java.time.DateTimeException: Unable to obtain ZoneId from TemporalAccessor: {},ISO resolved to 2020-11-16 of type java.time.format.Parsed
	at java.base/java.time.ZoneId.from(ZoneId.java:463)
	at java.base/java.time.ZonedDateTime.from(ZonedDateTime.java:554)
	... 4 more
 

4. Conclusion


In this article, we've seen how to use ZonedDateTime class in java 8 and what are the methods mostly used by the developers when working with the timezone dates.




2 comments:

  1. can you please check 3.6 Example output. It is giving exception!

    ReplyDelete
    Replies
    1. Hi Irshad, Section 3.6 prints two values. First value is printed as expected.
      Intention to show the exception if wrong date format is passed.

      Pass the right format such as ISO_ZONED_DATE_TIME to work without any exception.

      Please let me know if you face any issues.

      Happy learning!

      Delete

Please do not add any spam links in the comments section.