ZonedDateTime in Java with examples

In this tutorial, we will learn about the Java ZonedDateTime class.

ZonedDateTime in Java

Java ZonedDateTime class which is immutable. This class is a representation of date-time with a time-zone. ZonedDateTime class is used to store all the data and the time field with the utmost precision of nanoseconds.

For Example:-

‘2022-01-16T21:25:37.258+05:30[Asia/Delhi]’.

A ZonedDateTime holds a state equivalent to three different objects they are:-

  1. LocalDateTime
  2. ZoneId (specifies a time zone identifier, provides a rule for converting between an Instant and a LocalDateTime.)
  3. ZoneOffset. (represent the fixed zone offset from UTC zone)

Methods of ZonedDateTime 

  1. now
  2. of
  3. ofLocal
  4. ofInstant
  5. ofStrict
  6. from
  7. parse
  8. isSupported
  9. range
  10. get and many more…

CODE EXAMPLE

import java.time.ZonedDateTime;  
import java.time.Period;  
public class Time{  
  public static void main(String[] args) {  
      ZonedDateTime zone= ZonedDateTime.now();  
    ZonedDateTime m = zone.minus(Period.ofDays(126));  
    System.out.println(m);  
  }   
}

CODE EXPLANATION

  •  Import the following classes from java.time package to work with the date and time API in Java.
import java.time.ZonedDateTime; 

import java.time.Period;
  • Declare the main class and declare the main method which is in the entry point of any java program.
  • ZonedDateTime.now() which returns the current date-time default timezone of your machine.
  • zone. minus used to subtract the number of days from the machine.
  • Period.ofDays() accepts a single parameter which is the number of days to be parsed into the object.

OUTPUT

ZonedDateTime in Java

KEEP LEARNING!!!

Leave a Reply

Your email address will not be published.