In this guide, you will learn about the ZonedDateTime getZone() method in Java programming and how to use it with an example.
1. ZonedDateTime getZone() Method Overview
Definition:
The getZone() method of the ZonedDateTime class in Java is used to get the ZoneId of this ZonedDateTime. A ZoneId represents a time-zone identifier and provides rules for converting between an Instant and a LocalDateTime.
Syntax:
ZoneId getZone()
Parameters:
The method does not take any parameters.
Key Points:
- The getZone() method returns the ZoneId associated with this ZonedDateTime.
- A ZoneId is used to identify the rules used to convert an Instant to a LocalDateTime.
- Every ZonedDateTime is associated with a ZoneId that specifies the time-zone rules.
2. ZonedDateTime getZone() Method Example
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class ZonedDateTimeGetZoneExample {
public static void main(String[] args) {
// Creating a ZonedDateTime instance with the time-zone of Europe/Paris
ZonedDateTime zonedDateTime = ZonedDateTime.of(2023, 9, 20, 12, 34, 56, 0, ZoneId.of("Europe/Paris"));
System.out.println("ZonedDateTime: " + zonedDateTime);
// Getting the ZoneId of this ZonedDateTime
ZoneId zoneId = zonedDateTime.getZone();
System.out.println("ZoneId: " + zoneId);
// Getting ZoneId of a ZonedDateTime with system default time-zone
ZonedDateTime systemDefaultZonedDateTime = ZonedDateTime.now();
ZoneId defaultZoneId = systemDefaultZonedDateTime.getZone();
System.out.println("System Default ZoneId: " + defaultZoneId);
}
}
Output:
ZonedDateTime: 2023-09-20T12:34:56+02:00[Europe/Paris] ZoneId: Europe/Paris System Default ZoneId:
Explanation:
In this example, a ZonedDateTime instance was created with a specific time zone of Europe/Paris.
The getZone() method was then called to retrieve the ZoneId associated with this ZonedDateTime, which returned Europe/Paris. Additionally, the getZone() method was used to get the ZoneId of a ZonedDateTime created with the system's default time zone.
The actual output for the system default ZoneId will depend on the system configuration where the code is run.
Comments
Post a Comment
Leave Comment