简介

  • LocalDateTime总是表示本地日期和时间,要表示一个带时区的日期和时间,我们就需要ZonedDateTime
  • 可以简单地把ZonedDateTime理解成LocalDateTime加ZoneId。ZoneId是java.time引入的新的时区类,注意和旧的java.util.TimeZone区别
  • 要创建一个ZonedDateTime对象,有以下几种方法,一种是通过now()方法返回当前时间
  • 另一种方式是通过给一个LocalDateTime附加一个ZoneId,就可以变成ZonedDateTime

    实例

    ```java public class ZonedDateTimeTest { public static void main(String[] args) {
    1. // 默认时区
    2. ZonedDateTime zbj = ZonedDateTime.now();
    3. // 用指定时区获取当前时间
    4. ZonedDateTime zny = ZonedDateTime.now(ZoneId.of("America/New_York"));
    5. System.out.println(zbj);
    6. System.out.println(zny);
    } }

// 2022-02-17T19:40:41.847+08:00[Asia/Shanghai] // 2022-02-17T06:40:41.848-05:00[America/New_York]

```java
public class ZonedDateTimeTest {
    public static void main(String[] args) {
        LocalDateTime ldt = LocalDateTime.of(2019, 9, 15, 15, 16, 17);
        ZonedDateTime zbj = ldt.atZone(ZoneId.systemDefault());
        ZonedDateTime zny = ldt.atZone(ZoneId.of("America/New_York"));
        System.out.println(zbj);
        System.out.println(zny);
    }
}

// 2019-09-15T15:16:17+08:00[Asia/Shanghai]
// 2019-09-15T15:16:17-04:00[America/New_York]