$show=/label

Java 8 ZonedDateTime Examples

SHARE:

A quick guide to work with time zone dates in java 8 using ZonedDateTime API and examples to solve different realtime time zone problems.

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.




COMMENTS

BLOGGER: 2
  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.

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 ZonedDateTime Examples
Java 8 ZonedDateTime Examples
A quick guide to work with time zone dates in java 8 using ZonedDateTime API and examples to solve different realtime time zone problems.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi3zUHK4eFWLnAfFFLzhFL5GUNg36TSnp2q1FBtkKL0F4JT28u1LUqYg4xqpAdL3qeI1FiomMNXhM21AFPNPFt0BL9DjvehGM8xC0e9RF1PVwxwC8W1-ybZi6WPUiVxJBKOVqUAX9TslYQ/w640-h476/Java+8+ZonedDateTime+Examples.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi3zUHK4eFWLnAfFFLzhFL5GUNg36TSnp2q1FBtkKL0F4JT28u1LUqYg4xqpAdL3qeI1FiomMNXhM21AFPNPFt0BL9DjvehGM8xC0e9RF1PVwxwC8W1-ybZi6WPUiVxJBKOVqUAX9TslYQ/s72-w640-c-h476/Java+8+ZonedDateTime+Examples.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/11/java-zoneddatetime.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/11/java-zoneddatetime.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content