Java 8 – ZonedDateTime with method details and examples

In this article, we will discuss about newly introduced ZonedDateTime class in Java 1.8 version for dealing with date and time along with Zone information in program with ease and convenience.

Prior to introducing LocalDateLocalTimeLocalDateTime and ZonedDateTime in Java 1.8 version, we have to deal with java.util.Datejava.util.Calendarjava.sql.Timestampjava.sql.Time, java.util.TimeZone for date/time handling in Java which isn’t easy & straight-forward and there are few issues as mentioned below,

  • Thread-safety :- Existing Date/Time classes and its methods aren’t thread-safe and hence it’s not convenient to handle in concurrent/parallel environment
  • Not so-easy API design :- Existing Date/Time classes’ methods aren’t convenient to use in day-to-day programmer’s coding or development
  • Time-zone settings :- Developers or Programmer’s life becomes difficult while dealing with time zone settings in programs

Let’s move forward and discuss about java.time.ZonedDateTime introduced in Java 1.8 version

1. ZonedDateTime v/s LocalDateTime:

Before moving forward to detail out about ZonedDateTime, let’s understand what are the difference between LocalDateTime & ZonedDateTime and what extra information we get from using ZonedDateTime instead of using plain LocalDateTime

  • ZonedDateTime = LocalDateTime + Time-Zone
  • That’s ZonedDateTime provides all those information what LocalDateTime provide plus Zone information in the ISO-8601 calendar system
  • In the below illustration, we are printing ZonedDateTime & LocalDateTime twice
    • First in the system default zone (i.e., Asia/Calcutta)
    • Second, after providing ZoneId (America/Los_Angeles) as argument to overloaded now() method
  • Both ZonedDateTime & LocalDateTime prints current Date/time in their specific Zone
  • ZonedDateTime provides date-time to nano-second precision plus time-difference from Greenwich Mean Time (GMT) and time-zone information in square bracket like,
    • +05:30[Asia/Calcutta]
    • -07:00[America/Los_Angeles]
  • Note: Time-difference from Greenwich Mean Time is known as Offset

ZonedDateTimeVsLocalDateTime.java

package in.bench.resources.zoneddatetime.sorting;

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

public class ZonedDateTimeVsLocalDateTime {

	public static void main(String[] args) {

		// 1. LocalDateTime and ZonedDateTime in system default zone
		System.out.println("1. LocalDateTime and ZonedDateTime in system default zone - " 
				+ ZoneId.systemDefault());


		// 1.1 current date/time in default zone
		ZonedDateTime zonedDateTime = ZonedDateTime.now();
		System.out.println("\n1.1 ZonedDateTime  - " + zonedDateTime);

		// 1.2 current date/time in default zone
		LocalDateTime localDateTime = LocalDateTime.now();
		System.out.println("\n1.2 LocalDateTime - " + localDateTime);



		// 2. LocalDateTime and ZonedDateTime in America/Los_Angeles Zone 
		ZoneId zoneId = ZoneId.of("America/Los_Angeles");
		System.out.println("\n\n2. LocalDateTime and ZonedDateTime in America/Los_Angeles Zone");


		// 2.1 current date/time in specific/passed zone
		ZonedDateTime zonedDateTime2 = ZonedDateTime.now(zoneId);
		System.out.println("\n2.1 ZonedDateTime  - " + zonedDateTime2);


		// 2.2 current date/time in specific/passed zone
		LocalDateTime localDateTime2 = LocalDateTime.now(zoneId);
		System.out.println("\n2.2 LocalDateTime - " + localDateTime2);
	}
}

Output:

1. LocalDateTime and ZonedDateTime in system default zone - Asia/Calcutta

1.1 ZonedDateTime  - 2022-06-25T22:04:42.458655700+05:30[Asia/Calcutta]

1.2 LocalDateTime - 2022-06-25T22:04:42.458655700


2. LocalDateTime and ZonedDateTime in America/Los_Angeles Zone

2.1 ZonedDateTime  - 2022-06-25T09:34:42.459655700-07:00[America/Los_Angeles]

2.2 LocalDateTime - 2022-06-25T09:34:42.468655700

2. ZonedDateTime :

  • There are 3 ways to get/form a ZonedDateTime,
    1. First is to get current system date/time in default system time-zone using static factory method now() or get current system date/time in specific time-zone by providing ZoneId as argument to static factory method now(ZoneId)
    2. Second is to form a ZonedDateTime using static factory method of() passing year, month, day, hour, minute, second, nano and time-zone information (there are 3 variants)
    3. Third and final is to parse date/time/zone in String-form to ZonedDateTime using static factory method parse() such as 2007-12-03T10:15:30+01:00[Europe/Paris]
  • The fully qualified package/class name of ZonedDateTime is java.time.ZonedDateTime i.e.; ZonedDateTime is present under java.time package
  • Class declaration for ZonedDateTime is as follows,
package java.time;

public final class ZonedDateTime
        implements Temporal, ChronoZonedDateTime<LocalDate>, Serializable {
}

3. ZonedDateTime methods or APIs :

  • Important ZonedDateTime method details,
    • now() – get current date-time to nano-second precision from the system clock in the default time-zone
    • now(ZoneId) – get current date-time to nano-second precision from the system clock in the specific time-zone provided as method-argument
    • of() – get an instance of ZonedDateTime from a year, month, day, hour, minute, second, nanoseconds and time-zone passed
    • parse() – get an instance of ZonedDateTime from a text string in yyyy-MM-ddTHH:mm:ss.nnn+/-HH:mm[Continent/Region] or yyyy-MM-ddTHH:mm:ss+/-HH:mm[Continent/Region] or yyyy-MM-ddTHH:mm+/-HH:mm[Continent/Region] formats
    • getYear() – get the Year field from ZonedDateTime
    • getMonthValue() – get the month-of-year field from 1 to 12 from ZonedDateTime 
    • getMonth() – get the month-of-year field using the Month enum from ZonedDateTime 
    • getDayOfMonth() – get the day-of-month field from ZonedDateTime 
    • getDayOfWeek() – get the day-of-week field, which is an enum DayOfWeek from ZonedDateTime 
    • getDayOfYear() – get the day-of-year field from ZonedDateTime 
    • getHour() – get the hour-of-day field from ZonedDateTime 
    • getMinute() – get the minute-of-hour field from ZonedDateTime 
    • getSecond() – get the  second-of-minute field from ZonedDateTime 
    • getNano() – get the nano-of-second field from ZonedDateTime 
    • getZone() – get the time-zone field from ZonedDateTime such as ‘Europe/Paris’.
    • getOffset() – get the zone offset, such as ‘+01:00’
    • plusDays() – Returns a copy of this ZonedDateTime with the specified number of days added
    • plusWeeks() – Returns a copy of this ZonedDateTime with the specified number of weeks added
    • plusMonths() – Returns a copy of this ZonedDateTime with the specified number of months added
    • plusYears() – Returns a copy of this ZonedDateTime with the specified number of years added
    • plusNanos() – Returns a copy of this ZonedDateTime with the specified number of nanoseconds added
    • plusSeconds() – Returns a copy of this ZonedDateTime with the specified number of seconds added
    • plusMinutes() – Returns a copy of this ZonedDateTime with the specified number of minutes added
    • plusHours() – Returns a copy of this ZonedDateTime with the specified number of hours added
    • minusDays() – Returns a copy of this ZonedDateTime with the specified number of days subtracted
    • minusWeeks() – Returns a copy of this ZonedDateTime with the specified number of weeks subtracted
    • minusMonths() – Returns a copy of this ZonedDateTime with the specified number of months subtracted
    • minusYears() – Returns a copy of this ZonedDateTime with the specified number of years subtracted
    • minusNanos() – Returns a copy of this ZonedDateTime with the specified number of nanoseconds subtracted
    • minusSeconds() – Returns a copy of this ZonedDateTime with the specified number of seconds subtracted
    • minusMinutes() – Returns a copy of this ZonedDateTime with the specified number of minutes subtracted
    • minusHours() – Returns a copy of this ZonedDateTime with the specified number of hours subtracted
    • format() – Formats invoking date-time with time-zone information using the specified date formatter
    • withDayOfMonth() – Returns a copy of this ZonedDateTime with the day-of-month altered
    • withMonth() – Returns a copy of this ZonedDateTime with the month-of-year altered
    • withYear() – Returns a copy of this ZonedDateTime with the year altered
    • withHour() – Returns a copy of this ZonedDateTime with the hour-of-day altered
    • withMinute() – Returns a copy of this ZonedDateTime with the minute-of-hour altered
    • withSecond() – Returns a copy of this ZonedDateTime with the second-of-minute altered
    • withNano() – Returns a copy of this ZonedDateTime with the nano-of-second altered
    • withZoneSameInstant() – Returns a copy of this date-time with a different time-zone, retaining the instant

4. ZonedDateTime examples :

  1. ZonedDateTime.now() – get current date/time with time-zone information from system clock in the default zone
  2. ZonedDateTime.now(ZoneId) – get current date/time with time-zone information from system clock in the specific zone
  3. ZonedDateTime.of() – form ZonedDateTime passing Year, Month, Day, Hour, Minute, Second, Nano and Time-Zone fields
  4. ZonedDateTime.parse() – parse the date/time and time-zone in String-form to ZonedDateTime
  5. Adding day, week, month and year to ZonedDateTime using plusDays(), plusWeeks(), plusMonths() and plusYears() methods respectively
  6. Adding nano, second, minute and hour to ZonedDateTime using plusNanos(), plusSeconds(), plusMinutes() and plusHours() methods respectively
  7. Subtracting day, week, month and year from ZonedDateTime using minusDays(), minusWeeks(), minusMonths() and minusYears() methods respectively
  8. Subtracting nano, second, minute and hour from ZonedDateTime using minusNanos(), minusSeconds(), minusMinutes() and minusHours() methods respectively
  9. Formatting ZonedDateTime in different formats using DateTimeFormatter class
  10. Altering day, month, year, nano, second, minute, hour and time-zone fields with ZonedDateTime using withDayOfMonth(), withMonth(), withYear(), withNano(), withSecond(), withMinute(), withHour() and withZoneSameInstant() methods respectively

4.1 ZonedDateTime.now() method – get Current System Date/time in default zone

  • ZonedDateTime.now() method helps to get current system date/time in the default zone which will be in the yyyy-MM-ddTHH:mm:ss.nnn+/-HH:mm[Continent/Region] format
  • We can get year, month, day, hour, minute, second, nano-second and time-zone field/part from ZonedDateTime using different methods mentioned above and then we can form our own format as required like “dd.MM.yyyy HH:mm:ss.nnn
  • Zone used – default zone [Asia/Calcutta]

ZonedDateTimeExampleUsingNowMethod.java

package in.bench.resources.zoneddatetime.sorting;

import java.time.DayOfWeek;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public class ZonedDateTimeExampleUsingNowMethod {

	public static void main(String[] args) {

		// get current system date along with time in default zone
		ZonedDateTime zonedDateTime = ZonedDateTime.now();
		System.out.println("Current date/time in default zone is = " + zonedDateTime);


		// 1. Date part
		System.out.println("\n1. Date part from ZonedDateTime : \n");


		// 1.1 get YEAR part from current system date
		int year = zonedDateTime.getYear();
		System.out.println("Year is : " + year);


		// 1.2 get MONTH part from current system date
		int month = zonedDateTime.getMonthValue();
		System.out.println("Month is : " + month);


		// 1.3 get MONTH part from current system date
		Month monthInWords = zonedDateTime.getMonth();
		System.out.println("Month in Words is : " + monthInWords);


		// 1.4 get DAY part from current system date
		int day = zonedDateTime.getDayOfMonth();
		System.out.println("Day is : " + day);


		// 1.5 get DAY part from current system date
		DayOfWeek dayOfWeek = zonedDateTime.getDayOfWeek();
		System.out.println("Day of Week is : " + dayOfWeek);


		// 1.6 get DAY part from current system date
		int dayOfYear = zonedDateTime.getDayOfYear();
		System.out.println("Day of Year is : " + dayOfYear);



		// 2. Time part
		System.out.println("\n2. Time part from ZonedDateTime : \n");


		// 2.1 get HOUR value from current system time
		int hours = zonedDateTime.getHour();
		System.out.println("Hour is : " + hours);


		// 2.2 get MINUTE value from current system time
		int minutes = zonedDateTime.getMinute();
		System.out.println("Minutes is : " + minutes);


		// 2.3 get SECOND value from current system time
		int seconds = zonedDateTime.getSecond();
		System.out.println("Seconds is : " + seconds);


		// 2.4 get NANO SECOND value from current system time
		int nano = zonedDateTime.getNano();
		System.out.println("Nano Seconds is : " + nano);



		// 3. Zone part
		System.out.println("\n3. Zone part from ZonedDateTime : \n");


		// 3.1 get ZONE part from current system zone
		ZoneId zoneId = zonedDateTime.getZone();
		System.out.println("Date/time in which zone ? " + zoneId);


		// 3.2 get OFFSET part from current system zone
		ZoneOffset zoneOffset = zonedDateTime.getOffset();
		System.out.println("Offset  is : " + zoneOffset);
	}
}

Output:

Current date/time in default zone is = 2022-06-25T22:05:23.816746900+05:30[Asia/Calcutta]

1. Date part from ZonedDateTime : 

Year is : 2022
Month is : 6
Month in Words is : JUNE
Day is : 25
Day of Week is : SATURDAY
Day of Year is : 176

2. Time part from ZonedDateTime : 

Hour is : 22
Minutes is : 5
Seconds is : 23
Nano Seconds is : 816746900

3. Zone part from ZonedDateTime : 

Date/time in which zone ? Asia/Calcutta
Offset  is : +05:30

4.2 ZonedDateTime.now(ZoneId) method – get Current System Date/time in specific zone

  • ZonedDateTime.now(ZoneId) method helps to get current system date/time in specific zone which will be in the yyyy-MM-ddTHH:mm:ss.nnn+/-HH:mm[Continent/Region] format
  • We can get year, month, day, hour, minute, second, nano-second and time-zone field/part from ZonedDateTime using different methods mentioned above and then we can form our own format as required like “dd.MM.yyyy HH:mm:ss.nnn
  • Zone used – [America/Los_Angeles]

ZonedDateTimeExampleUsingNowMethod2.java

package in.bench.resources.zoneddatetime.sorting;

import java.time.DayOfWeek;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public class ZonedDateTimeExampleUsingNowMethod2 {

	public static void main(String[] args) {

		// ZoneId
		ZoneId zoneId = ZoneId.of("America/Los_Angeles");


		// get current date along with time in specific zone (America/Los_Angeles)
		ZonedDateTime zonedDateTime = ZonedDateTime.now(zoneId);
		System.out.println("Current date/time in specific zone is = " + zonedDateTime);


		// 1. Date part
		System.out.println("\n1. Date part from ZonedDateTime : \n");


		// 1.1 get YEAR part from current system date
		int year = zonedDateTime.getYear();
		System.out.println("Year is : " + year);


		// 1.2 get MONTH part from current system date
		int month = zonedDateTime.getMonthValue();
		System.out.println("Month is : " + month);


		// 1.3 get MONTH part from current system date
		Month monthInWords = zonedDateTime.getMonth();
		System.out.println("Month in Words is : " + monthInWords);


		// 1.4 get DAY part from current system date
		int day = zonedDateTime.getDayOfMonth();
		System.out.println("Day is : " + day);


		// 1.5 get DAY part from current system date
		DayOfWeek dayOfWeek = zonedDateTime.getDayOfWeek();
		System.out.println("Day of Week is : " + dayOfWeek);


		// 1.6 get DAY part from current system date
		int dayOfYear = zonedDateTime.getDayOfYear();
		System.out.println("Day of Year is : " + dayOfYear);



		// 2. Time part
		System.out.println("\n2. Time part from ZonedDateTime : \n");


		// 2.1 get HOUR value from current system time
		int hours = zonedDateTime.getHour();
		System.out.println("Hour is : " + hours);


		// 2.2 get MINUTE value from current system time
		int minutes = zonedDateTime.getMinute();
		System.out.println("Minutes is : " + minutes);


		// 2.3 get SECOND value from current system time
		int seconds = zonedDateTime.getSecond();
		System.out.println("Seconds is : " + seconds);


		// 2.4 get NANO SECOND value from current system time
		int nano = zonedDateTime.getNano();
		System.out.println("Nano Seconds is : " + nano);



		// 3. Zone part
		System.out.println("\n3. Zone part from ZonedDateTime : \n");


		// 3.1 get ZONE part from current system zone
		ZoneId zoneId2 = zonedDateTime.getZone();
		System.out.println("Date/time in which zone ? " + zoneId2);


		// 3.2 get OFFSET part from current system zone
		ZoneOffset zoneOffset = zonedDateTime.getOffset();
		System.out.println("Offset  is : " + zoneOffset);
	}
}

Output:

Current date/time in specific zone is = 2022-06-25T09:35:45.197069300-07:00[America/Los_Angeles]

1. Date part from ZonedDateTime : 

Year is : 2022
Month is : 6
Month in Words is : JUNE
Day is : 25
Day of Week is : SATURDAY
Day of Year is : 176

2. Time part from ZonedDateTime : 

Hour is : 9
Minutes is : 35
Seconds is : 45
Nano Seconds is : 197069300

3. Zone part from ZonedDateTime : 

Date/time in which zone ? America/Los_Angeles
Offset  is : -07:00

4.3 LocalDateTime.of() method – form Date/time

  • Passing year, month, day, hour, minute, second, nano-second and time-zone field/part to ZonedDateTime.of() method returns ZonedDateTime which will be in the yyyy-MM-ddTHH:mm:ss.nnn+/-HH:mm[Continent/Region] format
  • We can extract different fields like year, month, day, hour, minute, second, nano-second and time-zone from ZonedDateTime and then form our own format as required like “dd/MM/yyyy HH:mm:ss.nnn
  • Zone used – [Australia/Sydney]

ZonedDateTimeExampleUsingOfMethod.java

package in.bench.resources.zoneddatetime.sorting;

import java.time.DayOfWeek;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public class ZonedDateTimeExampleUsingOfMethod {

	public static void main(String[] args) {

		// ZoneId
		ZoneId zoneId = ZoneId.of("Australia/Sydney");


		// for specific date along with time
		ZonedDateTime zonedDateTime = ZonedDateTime.of(1950, 1, 26, 11, 45, 37, 987000000, zoneId);
		System.out.println("Date/time is = " + zonedDateTime);


		// 1. Date part
		System.out.println("\n1. Date part from ZonedDateTime : \n");


		// 1.1 get YEAR part from current system date
		int year = zonedDateTime.getYear();
		System.out.println("Year is : " + year);


		// 1.2 get MONTH part from current system date
		int month = zonedDateTime.getMonthValue();
		System.out.println("Month is : " + month);


		// 1.3 get MONTH part from current system date
		Month monthInWords = zonedDateTime.getMonth();
		System.out.println("Month in Words is : " + monthInWords);


		// 1.4 get DAY part from current system date
		int day = zonedDateTime.getDayOfMonth();
		System.out.println("Day is : " + day);


		// 1.5 get DAY part from current system date
		DayOfWeek dayOfWeek = zonedDateTime.getDayOfWeek();
		System.out.println("Day of Week is : " + dayOfWeek);


		// 1.6 get DAY part from current system date
		int dayOfYear = zonedDateTime.getDayOfYear();
		System.out.println("Day of Year is : " + dayOfYear);



		// 2. Time part
		System.out.println("\n2. Time part from ZonedDateTime : \n");


		// 2.1 get HOUR value from current system time
		int hours = zonedDateTime.getHour();
		System.out.println("Hour is : " + hours);


		// 2.2 get MINUTE value from current system time
		int minutes = zonedDateTime.getMinute();
		System.out.println("Minutes is : " + minutes);


		// 2.3 get SECOND value from current system time
		int seconds = zonedDateTime.getSecond();
		System.out.println("Seconds is : " + seconds);


		// 2.4 get NANO SECOND value from current system time
		int nano = zonedDateTime.getNano();
		System.out.println("Nano Seconds is : " + nano);



		// 3. Zone part
		System.out.println("\n3. Zone part from ZonedDateTime : \n");


		// 3.1 get ZONE part from current system zone
		ZoneId zoneId2 = zonedDateTime.getZone();
		System.out.println("Date/time in which zone ? " + zoneId2);


		// 3.2 get OFFSET part from current system zone
		ZoneOffset zoneOffset = zonedDateTime.getOffset();
		System.out.println("Offset  is : " + zoneOffset);
	}
}

Output:

Date/time is = 1950-01-26T11:45:37.987+10:00[Australia/Sydney]

1. Date part from ZonedDateTime : 

Year is : 1950
Month is : 1
Month in Words is : JANUARY
Day is : 26
Day of Week is : THURSDAY
Day of Year is : 26

2. Time part from ZonedDateTime : 

Hour is : 11
Minutes is : 45
Seconds is : 37
Nano Seconds is : 987000000

3. Zone part from ZonedDateTime : 

Date/time in which zone ? Australia/Sydney
Offset  is : +10:00

4.4 ZonedDateTime.parse() method – get Date/time/zone in String-form

  • Sometimes, we need to parse date/time with zone passed in String-form to ZonedDateTime, for that we can use ZonedDateTime.parse() method which will return ZonedDateTime in yyyy-MM-ddTHH:mm:ss.nnn+/-HH:mm[Continent/Region] format
  • While parsing Date/Time with Zone, value in String-form should be in either of the below formats only, otherwise java.time.format.DateTimeParseException will be thrown
    • yyyy-MM-ddTHH:mm:ss.nnn+/-HH:mm[Continent/Region]
    • yyyy-MM-ddTHH:mm:ss+/-HH:mm[Continent/Region]
    • yyyy-MM-ddTHH:mm+/-HH:mm[Continent/Region]
  • Zone used – [Australia/Sydney]

ZonedDateTimeExampleUsingParseMethod.java

package in.bench.resources.zoneddatetime.sorting;

import java.time.ZonedDateTime;

public class ZonedDateTimeExampleUsingParseMethod {

	public static void main(String[] args) {

		// 1. ZonedDateTime with all fields y, M, d, H, m, s, n and X, V
		String dateTimeZoneInStr1 = "1950-01-26T11:45:37.987654321+10:00[Australia/Sydney]";


		// 1.1 convert/parse dateInString to ZonedDateTime
		ZonedDateTime dateTimeZone1 = ZonedDateTime.parse(dateTimeZoneInStr1);
		System.out.println("1. Parsed Date/time (yyyy-MM-ddTHH:mm:ss.nnn+/-HH:mm[Continent/Region]) "
				+ "in specific zone is - \n" + dateTimeZone1);



		// 2. ZonedDateTime with fields y, M, d, H, m, s and X, V
		String dateTimeZoneInStr2 = "1950-01-26T11:45:37+10:00[Australia/Sydney]";


		// 2.1 convert/parse dateInString to ZonedDateTime
		ZonedDateTime dateTimeZone2 = ZonedDateTime.parse(dateTimeZoneInStr2);
		System.out.println("\n2. Parsed Date/time (yyyy-MM-ddTHH:mm:ss+/-HH:mm[Continent/Region]) "
				+ "in specific zone is - \n" + dateTimeZone2);



		// 3. ZonedDateTime with fields y, M, d, H, m and X, V
		String dateTimeZoneInStr3 = "1950-01-26T11:45+10:00[Australia/Sydney]";


		// 3.1 convert/parse dateInString to ZonedDateTime
		ZonedDateTime dateTimeZone3 = ZonedDateTime.parse(dateTimeZoneInStr3);
		System.out.println("\n3. Parsed Date/time (yyyy-MM-ddTHH:mm+/-HH:mm[Continent/Region]) "
				+ "in specific zone is - \n" + dateTimeZone3);
	}
}

Output:

1. Parsed Date/time (yyyy-MM-ddTHH:mm:ss.nnn+/-HH:mm[Continent/Region]) in specific zone is - 
1950-01-26T11:45:37.987654321+10:00[Australia/Sydney]

2. Parsed Date/time (yyyy-MM-ddTHH:mm:ss+/-HH:mm[Continent/Region]) in specific zone is - 
1950-01-26T11:45:37+10:00[Australia/Sydney]

3. Parsed Date/time (yyyy-MM-ddTHH:mm+/-HH:mm[Continent/Region]) in specific zone is - 
1950-01-26T11:45+10:00[Australia/Sydney]

4.5 Adding Day/Week/Month/Year to ZonedDateTime :

  1. Add 5 Days to ZonedDateTime using plusDays() method
  2. Add 2 Weeks to ZonedDateTime using plusWeeks() method
  3. Add 3 Months to ZonedDateTime using plusMonths() method
  4. Add 1 Year to ZonedDateTime using plusYears() method
  5. Zone used – [Africa/Harare]

AddDatePartWithZonedDateTime.java

package in.bench.resources.zoneddatetime.sorting;

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

public class AddDatePartWithZonedDateTime {

	public static void main(String[] args) {

		// ZoneId
		ZoneId zoneId = ZoneId.of("Africa/Harare");


		// 1. get Zoned date/time with zone info passed
		ZonedDateTime zonedDateTime = ZonedDateTime.now(zoneId);
		System.out.println("1. Zoned Date/time in specific zone is = " 
				+ zonedDateTime);


		// 1.1 add 5 days with zone date/time
		ZonedDateTime add_5_Days = zonedDateTime.plusDays(5);
		System.out.println("\n1.1 After adding 5 Days to Zoned Date/time is = " 
				+ add_5_Days);


		// 1.2 add 2 weeks to zone date/time
		ZonedDateTime add_2_Weeks = zonedDateTime.plusWeeks(2);
		System.out.println("\n1.2 After adding 2 Weeks to Zoned Date/time is = " 
				+ add_2_Weeks);


		// 1.3 add 3 months to zone date/time
		ZonedDateTime add_3_Months = zonedDateTime.plusMonths(3);
		System.out.println("\n1.3 After adding 3 Months to Zoned Date/time is = " 
				+ add_3_Months);


		// 1.4 add 1 year to zone date/time
		ZonedDateTime add_1_Year = zonedDateTime.plusYears(1);
		System.out.println("\n1.4 After adding 1 Year to Zoned Date/time is = " 
				+ add_1_Year);
	}
}

Output:

1. Zoned Date/time in specific zone is = 2022-06-25T18:36:44.276680300+02:00[Africa/Harare]

1.1 After adding 5 Days to Zoned Date/time is = 2022-06-30T18:36:44.276680300+02:00[Africa/Harare]

1.2 After adding 2 Weeks to Zoned Date/time is = 2022-07-09T18:36:44.276680300+02:00[Africa/Harare]

1.3 After adding 3 Months to Zoned Date/time is = 2022-09-25T18:36:44.276680300+02:00[Africa/Harare]

1.4 After adding 1 Year to Zoned Date/time is = 2023-06-25T18:36:44.276680300+02:00[Africa/Harare]

4.6 Adding Nano/Second/Minute/Hour to ZonedDateTime :

  1. Add 125 Nanos to ZonedDateTime using plusNanos() method
  2. Add 37 Seconds to ZonedDateTime using plusSeconds() method
  3. Add 19 Minutes to ZonedDateTime using plusMinutes() method
  4. Add 5 Hours to ZonedDateTime using plusHours() method
  5. Zone used – [Europe/Paris]

AddTimePartWithZonedDateTime.java

package in.bench.resources.zoneddatetime.sorting;

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

public class AddTimePartWithZonedDateTime {

	public static void main(String[] args) {

		// ZoneId
		ZoneId zoneId = ZoneId.of("Europe/Paris");


		// 1. get Zoned Date/time
		ZonedDateTime zonedDateTime = ZonedDateTime.now(zoneId);
		System.out.println("1. Zoned Date/time is - " + zonedDateTime);


		// 1.1 add 125 NanoSeconds to Zoned Date/time
		ZonedDateTime add_125_Nanos = zonedDateTime.plusNanos(125);
		System.out.println("\n1.1 After adding 125 Nano Seconds to Zoned Date/time is - " 
				+ add_125_Nanos);


		// 1.2 add 37 Seconds to Zoned Date/time
		ZonedDateTime add_37_Seconds = zonedDateTime.plusSeconds(37);
		System.out.println("\n1.2 After adding 37 Seconds to Zoned Date/time is - " 
				+ add_37_Seconds);


		// 1.3 add 19 Minutes to Zoned Date/time
		ZonedDateTime add_19_Minutes = zonedDateTime.plusMinutes(19);
		System.out.println("\n1.3 After adding 19 Minutes to Zoned Date/time is - " 
				+ add_19_Minutes);


		// 1.4 add 5 Hours to Zoned Date/time
		ZonedDateTime add_5_Hours = zonedDateTime.plusHours(5);
		System.out.println("\n1.4 After adding 5 Hours to Zoned Date/time is - " 
				+ add_5_Hours);
	}
}

Output:

1. Zoned Date/time is - 2022-06-25T18:37:03.378726100+02:00[Europe/Paris]

1.1 After adding 125 Nano Seconds to Zoned Date/time is - 2022-06-25T18:37:03.378726225+02:00[Europe/Paris]

1.2 After adding 37 Seconds to Zoned Date/time is - 2022-06-25T18:37:40.378726100+02:00[Europe/Paris]

1.3 After adding 19 Minutes to Zoned Date/time is - 2022-06-25T18:56:03.378726100+02:00[Europe/Paris]

1.4 After adding 5 Hours to Zoned Date/time is - 2022-06-25T23:37:03.378726100+02:00[Europe/Paris]

4.7 Subtracting Day/Week/Month/Year from ZonedDateTime :

  1. Subtract 5 Days from ZonedDateTime using minusDays() method
  2. Subtract 2 Weeks from ZonedDateTime using minusWeeks() method
  3. Subtract 3 Months from ZonedDateTime using minusMonths() method
  4. Subtract 1 Year from ZonedDateTime using minusYears() method
  5. Zone used – [Asia/Shanghai]

SubtractDatePartFromZonedDateTime.java

package in.bench.resources.zoneddatetime.sorting;

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

public class SubtractDatePartFromZonedDateTime {

	public static void main(String[] args) {

		// ZoneId
		ZoneId zoneId = ZoneId.of("Asia/Shanghai");


		// 1. get Zoned Date/time
		ZonedDateTime zonedDateTime = ZonedDateTime.now(zoneId);
		System.out.println("1. Zoned Date/time is - " + zonedDateTime);


		// 1.1 subtract 5 days from Zoned Date/time
		ZonedDateTime subtract_5_Days = zonedDateTime.minusDays(5);
		System.out.println("\n1.1 After subtracting 5 Days from Zoned Date/time is - " 
				+ subtract_5_Days);


		// 1.2 subtract 2 weeks from Zoned Date/time
		ZonedDateTime subtract_2_Weeks = zonedDateTime.minusWeeks(2);
		System.out.println("\n1.2 After subtracting 2 Weeks from Zoned Date/time is - " 
				+ subtract_2_Weeks);


		// 1.3 subtract 3 months from Zoned Date/time
		ZonedDateTime subtract_3_Months = zonedDateTime.minusMonths(3);
		System.out.println("\n1.3 After subtracting 3 Months from Zoned Date/time is - " 
				+ subtract_3_Months);


		// 1.4 subtract 1 year from Zoned Date/time
		ZonedDateTime subtract_1_Year = zonedDateTime.minusYears(1);
		System.out.println("\n1.4 After subtracting 1 Year from Zoned Date/time is - " 
				+ subtract_1_Year);
	}
}

Output:

1. Zoned Date/time is - 2022-06-26T00:37:43.447657200+08:00[Asia/Shanghai]

1.1 After subtracting 5 Days from Zoned Date/time is - 2022-06-21T00:37:43.447657200+08:00[Asia/Shanghai]

1.2 After subtracting 2 Weeks from Zoned Date/time is - 2022-06-12T00:37:43.447657200+08:00[Asia/Shanghai]

1.3 After subtracting 3 Months from Zoned Date/time is - 2022-03-26T00:37:43.447657200+08:00[Asia/Shanghai]

1.4 After subtracting 1 Year from Zoned Date/time is - 2021-06-26T00:37:43.447657200+08:00[Asia/Shanghai]

4.8 Subtracting Nano/Second/Minute/Hour from ZonedDateTime :

  1. Subtract 125 Nanos from ZonedDateTime using minusNanos() method
  2. Subtract 37 Seconds from ZonedDateTime using minusSeconds() method
  3. Subtract 19 Minutes from ZonedDateTime using minusMinutes() method
  4. Subtract 5 Hours from ZonedDateTime using minusHours() method
  5. Zone used – [Pacific/Auckland]

SubtractTimePartFromZonedDateTime.java

package in.bench.resources.zoneddatetime.sorting;

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

public class SubtractTimePartFromZonedDateTime {

	public static void main(String[] args) {

		// ZoneId
		ZoneId zoneId = ZoneId.of("Pacific/Auckland");


		// 1. get Zoned Date/time
		ZonedDateTime zonedDateTime = ZonedDateTime.now(zoneId);
		System.out.println("1. Zoned Date/time is - " + zonedDateTime);


		// 1.1 subtract 125 NanoSeconds from Zoned Date/time
		ZonedDateTime sub_125_Nanos = zonedDateTime.minusNanos(125);
		System.out.println("\n1.1 After subtracting 125 Nano Seconds from Zoned Date/time is - \n" 
				+ sub_125_Nanos);


		// 1.2 subtract 37 Seconds from Zoned Date/time
		ZonedDateTime sub_37_Seconds = zonedDateTime.minusSeconds(37);
		System.out.println("\n1.2 After subtracting 37 Seconds from Zoned Date/time is - \n" 
				+ sub_37_Seconds);


		// 1.3 subtract 19 Minutes from Zoned Date/time
		ZonedDateTime sub_19_Minutes = zonedDateTime.minusMinutes(19);
		System.out.println("\n1.3 After subtracting 19 Minutes from Zoned Date/time is - \n" 
				+ sub_19_Minutes);


		// 1.4 subtract 5 Hours from Zoned Date/time
		ZonedDateTime sub_5_Hours = zonedDateTime.minusHours(5);
		System.out.println("\n1.4 After subtracting 5 Hours from Zoned Date/time is - \n" 
				+ sub_5_Hours);
	}
}

Output:

1. Zoned Date/time is - 2022-06-26T04:42:56.157263400+12:00[Pacific/Auckland]

1.1 After subtracting 125 Nano Seconds from Zoned Date/time is - 
2022-06-26T04:42:56.157263275+12:00[Pacific/Auckland]

1.2 After subtracting 37 Seconds from Zoned Date/time is - 
2022-06-26T04:42:19.157263400+12:00[Pacific/Auckland]

1.3 After subtracting 19 Minutes from Zoned Date/time is - 
2022-06-26T04:23:56.157263400+12:00[Pacific/Auckland]

1.4 After subtracting 5 Hours from Zoned Date/time is - 
2022-06-25T23:42:56.157263400+12:00[Pacific/Auckland]

4.9 Formatting ZonedDateTime using DateTimeFormatter:

  • We can convert default ISO_LOCAL_DATE_TIME ZonedDateTime format yyyy-MM-ddTHH:mm:ss.nnn+/-HH:mm[Continent/Region] to any other formats using ZonedDateTime.format() method by passing DateTimeFormatter class as argument with required pattern in String-form
  • In this illustration, we are using 6 different custom formats as mentioned below,
    1. DateTimeFormatter.ofPattern(“dd.MM.yyyy“)
    2. DateTimeFormatter.ofPattern(“dd-MMM-yyyy“)
    3. DateTimeFormatter.ofPattern(“dd-MM-yyyy HH:mm“)
    4. DateTimeFormatter.ofPattern(“dd-MM-yyyy HH:mm:ss“)
    5. DateTimeFormatter.ofPattern(“dd-MM-yyyy HH:mm:ss.nnn“)
    6. DateTimeFormatter.ofPattern(“dd-MM-yyyy HH:mm:ss.nnn O [VV]“)
  • Zone used – [America/Indiana/Indianapolis]

FormattingZonedDateTimeUsingFormatMethod.java

package in.bench.resources.zoneddatetime.sorting;

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

public class FormattingZonedDateTimeUsingFormatMethod {

	public static void main(String[] args) {

		// ZoneId
		ZoneId zoneId = ZoneId.of("America/Indiana/Indianapolis");


		// 1. get Zoned Date/time
		ZonedDateTime zonedDateTime = ZonedDateTime.now(zoneId);
		System.out.println("1. Zoned Date/time in ISO_ZONED_DATE_TIME format is = \n"
				+ zonedDateTime);


		// 1.1 format ZonedDateTime to dd.MM.yyyy
		String formattedDate = zonedDateTime.format(DateTimeFormatter
				.ofPattern("dd.MM.yyyy"));
		System.out.println("\n1.1 Zoned Date/time in dd.MM.yyyy format is = "
				+ formattedDate);


		// 1.2 format ZonedDateTime to dd-MMM-yyyy
		String formattedDate2 = zonedDateTime.format(DateTimeFormatter
				.ofPattern("dd-MMM-yyyy"));
		System.out.println("\n1.2 Zoned Date/time in dd-MMM-yyyy format is = " 
				+ formattedDate2);


		// 1.3 format ZonedDateTime to dd-MM-yyyy HH:mm
		String formattedDate3 = zonedDateTime.format(DateTimeFormatter
				.ofPattern("dd-MM-yyyy HH:mm"));
		System.out.println("\n1.3 Zoned Date/time in dd-MM-yyyy HH:mm format is = " 
				+ formattedDate3);


		// 1.4 format ZonedDateTime to dd-MM-yyyy HH:mm:ss
		String formattedDate4 = zonedDateTime.format(DateTimeFormatter
				.ofPattern("dd-MM-yyyy HH:mm:ss"));
		System.out.println("\n1.4 Zoned Date/time in dd-MM-yyyy HH:mm:ss format is = " 
				+ formattedDate4);


		// 1.5 format ZonedDateTime to dd-MM-yyyy HH:mm:ss.nnn
		String formattedDate5 = zonedDateTime.format(DateTimeFormatter
				.ofPattern("dd-MM-yyyy HH:mm:ss.nnn"));
		System.out.println("\n1.5 Zoned Date/time in dd-MM-yyyy HH:mm:ss.nnn format is = "
				+ formattedDate5);


		// 1.6 format ZonedDateTime to dd-MM-yyyy HH:mm:ss.nnn O [VV]
		String formattedDate6 = zonedDateTime.format(DateTimeFormatter
				.ofPattern("dd-MM-yyyy HH:mm:ss.nnn O [VV]"));
		System.out.println("\n1.6 Zoned Date/time in dd-MM-yyyy HH:mm:ss.nnn O [VV] format is = \n"
				+ formattedDate6);
	}
}

Output:

1. Zoned Date/time in ISO_ZONED_DATE_TIME format is = 
2022-06-25T12:43:14.544841800-04:00[America/Indiana/Indianapolis]

1.1 Zoned Date/time in dd.MM.yyyy format is = 25.06.2022

1.2 Zoned Date/time in dd-MMM-yyyy format is = 25-Jun-2022

1.3 Zoned Date/time in dd-MM-yyyy HH:mm format is = 25-06-2022 12:43

1.4 Zoned Date/time in dd-MM-yyyy HH:mm:ss format is = 25-06-2022 12:43:14

1.5 Zoned Date/time in dd-MM-yyyy HH:mm:ss.nnn format is = 25-06-2022 12:43:14.544841800

1.6 Zoned Date/time in dd-MM-yyyy HH:mm:ss.nnn O [VV] format is = 
25-06-2022 12:43:14.544841800 GMT-4 America/Indiana/Indianapolis

4.10 Altering Day/Month/Year & Nano/Second/Minute/Hour & ZoneId fields with ZonedDateTime:

  • Altering Day, Month, Year, Hour, Minute, Second, Nano-second and time-zone field/part of ZonedDateTime is possible with the help below methods,
    • withDayOfMonth() – This method alters day-of-month part/field of the invoking ZonedDateTime
    • withMonth() – This method alters month-of-year part/field of the invoking ZonedDateTime
    • withYear() – This method alters year part/field of the invoking ZonedDateTime
    • withHour() – This method alters hour part/field of the invoking ZonedDateTime
    • withMinute() – This method alters minute part/field of the invoking ZonedDateTime
    • withSecond() – This method alters second part/field of the invoking ZonedDateTime
    • withNano() -This method alters nano-second part/field of the invoking ZonedDateTime
    • withZoneSameInstant() – This method alters time-zone part/field of the invoking ZonedDateTime, retaining the instant
  • Zone used – [America/Argentina/Buenos_Aires] and [America/Chicago]

AlterZonedDateTime.java

package in.bench.resources.zoneddatetime.sorting;

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

public class AlterZonedDateTime {

	public static void main(String[] args) {

		// ZoneId
		ZoneId zoneId = ZoneId.of("America/Argentina/Buenos_Aires");


		// 1. get Zoned Date/time
		ZonedDateTime zonedDateTime = ZonedDateTime.now(zoneId);
		System.out.println("1. Zoned Date/time in ISO_ZONED_DATE_TIME format is = \n" 
				+ zonedDateTime);


		// 1.1 alter day field/part in Zoned Date/time
		ZonedDateTime dateAltered = zonedDateTime.withDayOfMonth(27);
		System.out.println("\n1.1 Day (27) altered in Zoned Date/time is = \n" 
				+ dateAltered);


		// 1.2 alter month field/part in Zoned Date/time
		ZonedDateTime monthAltered = zonedDateTime.withMonth(7);
		System.out.println("\n1.2 Month (7) altered in Zoned Date/time is = \n" 
				+ monthAltered);


		// 1.3 alter year field/part in Zoned Date/time
		ZonedDateTime yearAltered = zonedDateTime.withYear(2023);
		System.out.println("\n1.3 Year (2023) altered in Zoned Date/time is = \n" 
				+ yearAltered);


		// 1.4 alter hour field/part in Zoned Date/time
		ZonedDateTime hourAltered = zonedDateTime.withHour(5);
		System.out.println("\n1.4 Hour (5) altered in Zoned Date/time is = \n" 
				+ hourAltered);


		// 1.5 alter minute field/part in Zoned Date/time
		ZonedDateTime minuteAltered = zonedDateTime.withMinute(19);
		System.out.println("\n1.5 Minute (19) altered in Zoned Date/time is = \n" 
				+ minuteAltered);


		// 1.6 alter second field/part in Zoned Date/time
		ZonedDateTime secondAltered = zonedDateTime.withSecond(47);
		System.out.println("\n1.6 Second (47) altered in Zoned Date/time is = \n" 
				+ secondAltered);


		// 1.7 alter nano second field/part in Zoned Date/time
		ZonedDateTime nanoAltered = zonedDateTime.withNano(125);
		System.out.println("\n1.7 Nano Second (125) altered in Zoned Date/time is = \n" 
				+ nanoAltered);


		// 1.8 alter zone field/part in Zoned Date/time
		ZonedDateTime zoneAltered = zonedDateTime.withZoneSameInstant(ZoneId.of("America/Chicago"));
		System.out.println("\n1.8 Zone (America/Chicago) altered in Zoned Date/time is = \n" 
				+ zoneAltered);
	}
}

Output:

1. Zoned Date/time in ISO_ZONED_DATE_TIME format is = 
2022-06-25T13:43:38.033654-03:00[America/Argentina/Buenos_Aires]

1.1 Day (27) altered in Zoned Date/time is = 
2022-06-27T13:43:38.033654-03:00[America/Argentina/Buenos_Aires]

1.2 Month (7) altered in Zoned Date/time is = 
2022-07-25T13:43:38.033654-03:00[America/Argentina/Buenos_Aires]

1.3 Year (2023) altered in Zoned Date/time is = 
2023-06-25T13:43:38.033654-03:00[America/Argentina/Buenos_Aires]

1.4 Hour (5) altered in Zoned Date/time is = 
2022-06-25T05:43:38.033654-03:00[America/Argentina/Buenos_Aires]

1.5 Minute (19) altered in Zoned Date/time is = 
2022-06-25T13:19:38.033654-03:00[America/Argentina/Buenos_Aires]

1.6 Second (47) altered in Zoned Date/time is = 
2022-06-25T13:43:47.033654-03:00[America/Argentina/Buenos_Aires]

1.7 Nano Second (125) altered in Zoned Date/time is = 
2022-06-25T13:43:38.000000125-03:00[America/Argentina/Buenos_Aires]

1.8 Zone (America/Chicago) altered in Zoned Date/time is = 
2022-06-25T11:43:38.033654-05:00[America/Chicago]

Q) How to get all zone information ?

AllZoneInformation.java

package in.bench.resources.zoneddatetime.sorting;

import java.time.ZoneId;
import java.util.Map;

public class AllZoneInformation {

	public static void main(String[] args) {

		// get short IDs for zone
		System.out.println("Java 8 Date/Time API - All zone information :- \n");
		Map<String, String> zoneIdMap = ZoneId.SHORT_IDS;


		// iterate through all zones after sorting
		zoneIdMap
		.entrySet()
		.stream()
		.sorted(Map.Entry.comparingByKey())
		.forEach(entry -> System.out.println(
				"Key : " + entry.getKey() + "\t Value : + " + entry.getValue()
				));
	}
}

Output:

Java 8 Date/Time API - All zone information :- 

Key : ACT	 Value : + Australia/Darwin
Key : AET	 Value : + Australia/Sydney
Key : AGT	 Value : + America/Argentina/Buenos_Aires
Key : ART	 Value : + Africa/Cairo
Key : AST	 Value : + America/Anchorage
Key : BET	 Value : + America/Sao_Paulo
Key : BST	 Value : + Asia/Dhaka
Key : CAT	 Value : + Africa/Harare
Key : CNT	 Value : + America/St_Johns
Key : CST	 Value : + America/Chicago
Key : CTT	 Value : + Asia/Shanghai
Key : EAT	 Value : + Africa/Addis_Ababa
Key : ECT	 Value : + Europe/Paris
Key : EST	 Value : + -05:00
Key : HST	 Value : + -10:00
Key : IET	 Value : + America/Indiana/Indianapolis
Key : IST	 Value : + Asia/Kolkata
Key : JST	 Value : + Asia/Tokyo
Key : MIT	 Value : + Pacific/Apia
Key : MST	 Value : + -07:00
Key : NET	 Value : + Asia/Yerevan
Key : NST	 Value : + Pacific/Auckland
Key : PLT	 Value : + Asia/Karachi
Key : PNT	 Value : + America/Phoenix
Key : PRT	 Value : + America/Puerto_Rico
Key : PST	 Value : + America/Los_Angeles
Key : SST	 Value : + Pacific/Guadalcanal
Key : VST	 Value : + Asia/Ho_Chi_Minh

Q) How to get Default zone information ?

  • ZoneId.systemDefault(); – provides default zone information

DefaultZoneInformation.java

package in.bench.resources.zoneddatetime.sorting;

import java.time.ZoneId;

public class DefaultZoneInformation {

	public static void main(String[] args) {

		// get default system zone info
		ZoneId zoneId = ZoneId.systemDefault();


		// print to console
		System.out.println("Defaul system zone is = " + zoneId);
	}
}

Output:

Defaul system zone is = Asia/Calcutta

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 - Display all Zones and its Offset using ZoneId and ZoneOffset
Java 8 – LocalDateTime with method details and examples