日历中的 toInstant() 以格林威治标准时间而不是本地时间显示

toInstant() in Calendar is showing in GMT instead of Local time

我正在尝试将 Calendar 实例转换为 instant,我按如下方式进行操作

    Calendar cal = new GregorianCalendar();
    System.out.println(cal.getTime());
    Instant inst = cal.toInstant();
    System.out.println(inst.toString());

并且,它的输出如下

Fri Oct 30 17:23:40 IST 2015

2015-10-30T11:53:40.037Z

所以,我的问题是关于 Calendar 和 instant 的输出差异。即时的输出是格林威治标准时间而不是当地时间。 我没有看到任何文档说 Instant class 只给出格林威治标准时间的日期。所以,我不确定为什么会这样。

Invoking toString on an Instant produces output like the following:

2013-05-30T23:38:23.085Z

This format follows the ISO-8601 standard for representing date and time.

看看:

Rawat 的 是正确的。根据定义,Instant 始终采用 UTC。

toString 方法生成的字符串表示格式是标准的,由 ISO 8601 定义。

Instant class 是 Java 8 及更高版本中内置的 java.time 框架的一部分。此框架中的新 classes 取代了 Java 早期的旧 java.util.Date/.Calendar classes。

避免使用旧的 classes,因为它们非常麻烦。不要混淆新旧。 toInstant 等转换方法仅适用于与旧代码的互操作尚未针对新类型进行更新的情况。

要将 Instant 调整为时区,请通过 ZoneId 对象指定时区以生成 ZonedDateTime

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

不要被LocalDateTimeclass中的"Local"搞糊涂了。 class 代表日期时间的模糊概念。它适用于任何特定时区,因此与时间轴无关。