📌  相关文章
📜  Java中的 ChronoZonedDateTime withZoneSameLocal() 方法及示例

📅  最后修改于: 2022-05-13 01:54:52.965000             🧑  作者: Mango

Java中的 ChronoZonedDateTime withZoneSameLocal() 方法及示例

ChronoZonedDateTime接口的withZoneSameLocal()方法用于通过更改时区和不带瞬间返回此 ChronoZonedDateTime 对象的副本。此方法基于保留相同瞬间,因此本地时间线中的间隙和重叠具有对结果没有影响。

句法:

ChronoZonedDateTime withZoneSameLocal(ZoneId zone)

参数:此方法接受一个参数zone来更改时区。它不应该为空。

返回值:此方法基于此日期时间与请求的区域返回ChronoZonedDateTime

下面的程序说明了 withZoneSameLocal() 方法:

方案一:

// Java program to demonstrate
// ChronoZonedDateTime.withZoneSameLocal() method
  
import java.time.*;
import java.time.chrono.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a ChronoZonedDateTime object
        ChronoZonedDateTime zonedDT
            = ZonedDateTime
                  .parse(
                      "2018-12-06T19:21:12.123+05:30[Asia/Calcutta]");
  
        // print ChronoZonedDateTime
        System.out.println("ChronoZonedDateTime of Calcutta: "
                           + zonedDT);
  
        // apply withZoneSameLocal()
        ChronoZonedDateTime zonedDT2
            = zonedDT
                  .withZoneSameLocal(
                      ZoneId.of("Pacific/Fiji"));
  
        // print ChronoZonedDateTime after withZoneSameLocal()
        System.out.println("ChronoZonedDateTime of Fuji: "
                           + zonedDT2);
    }
}
输出:
ChronoZonedDateTime of Calcutta: 2018-12-06T19:21:12.123+05:30[Asia/Calcutta]
ChronoZonedDateTime of Fuji: 2018-12-06T19:21:12.123+13:00[Pacific/Fiji]

方案二:

// Java program to demonstrate
// ChronoZonedDateTime.withZoneSameLocal() method
  
import java.time.*;
import java.time.chrono.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a ChronoZonedDateTime object
        ChronoZonedDateTime zonedDT
            = ZonedDateTime
                  .parse(
                      "2018-10-25T23:12:31.123+02:00[Europe/Paris]");
  
        // print ChronoZonedDateTime
        System.out.println("ChronoZonedDateTime of Calcutta: "
                           + zonedDT);
  
        // apply withZoneSameLocal()
        ChronoZonedDateTime zonedDT2
            = zonedDT
                  .withZoneSameLocal(
                      ZoneId.of("Canada/Yukon"));
  
        // print ChronoZonedDateTime after withZoneSameLocal()
        System.out.println("ChronoZonedDateTime of yukon: "
                           + zonedDT2);
    }
}
输出:
ChronoZonedDateTime of Calcutta: 2018-10-25T23:12:31.123+02:00[Europe/Paris]
ChronoZonedDateTime of yukon: 2018-10-25T23:12:31.123-07:00[Canada/Yukon]

参考: https://docs.oracle.com/javase/9/docs/api/ Java/time/chrono/ChronoZonedDateTime.html#withZoneSameLocal-java.time.ZoneId-