Java LocalDateTime Class | atZone() Method with Example

LocalDateTime Class atZone() method: Here, we are going to learn about the atZone() method of LocalDateTime Class with its syntax and example.
Submitted by Preeti Jain, on June 04, 2020

LocalDateTime Class atZone() method

  • atZone() method is available in java.time package.
  • atZone() method is used to create a ZonedDateTime by merging this LocalDateTime (date-time) to the given zone.
  • atZone() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • atZone() method does not throw an exception at the time of representing LocalDateTime.

Syntax:

    public ZonedDateTime atZone(ZoneId zo);

Parameter(s):

  • ZoneId zo – represents the zone to merge with this LocalDateTime.

Return value:

The return type of this method is ZonedDateTime, it returns ZonedDateTime object that holds the value merged this LocalDateTime with the given zone.

Example:

// Java program to demonstrate the example 
// of atZone(ZoneId zo) method of LocalDateTime

import java.time.*;

public class AtZoneOfLocalDateTime {
    public static void main(String args[]) {
        // Instantiates two LocalDateTime
        // and a ZonedId
        LocalDateTime da_ti1 = LocalDateTime.parse("2005-10-05T10:10:10");
        LocalDateTime da_ti2 = LocalDateTime.now();
        ZoneId zo = ZoneId.of("Africa/Accra");

        // Display da_ti1, da_ti2
        // and zo
        System.out.println("LocalDateTime da_ti1 and da_ti2: ");
        System.out.println("da_ti1: " + da_ti1);
        System.out.println("da_ti2: " + da_ti2);
        System.out.println();
        System.out.println("ZoneId zo: ");
        System.out.println("zo: " + zo);


        System.out.println();

        // Here, this method creates a ZonedDateTime
        // by merging this date-time (da_ti1)
        // with the given zone (zo) i.e. 
        // da_ti1 + zo
        ZonedDateTime zo_da_time = da_ti1.atZone(zo);

        // Display updated zo_da_time
        System.out.println("da_ti1.atZone(zo): " + zo_da_time);

        // Here, this method creates a ZonedDateTime
        // by merging this date-time (da_ti2)
        // with the given zone 
        // (ZoneId.of("Africa/Asmara")) i.e. 
        // da_ti2 + zone
        zo_da_time = da_ti2.atZone(ZoneId.of("Africa/Asmara"));

        // Display updated zo_da_time
        System.out.println("da_ti2.atZone(ZoneId.of(Africa/Asmara)): " + zo_da_time);
    }
}

Output

LocalDateTime da_ti1 and da_ti2: 
da_ti1: 2005-10-05T10:10:10
da_ti2: 2020-06-04T08:10:01.516588

ZoneId zo: 
zo: Africa/Accra

da_ti1.atZone(zo): 2005-10-05T10:10:10Z[Africa/Accra]
da_ti2.atZone(ZoneId.of(Africa/Asmara)): 2020-06-04T08:10:01.516588+03:00[Africa/Asmara]


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.