日历中的toInstant()以GMT(而不是本地时间)显示 [英] toInstant() in Calendar is showing in GMT instead of Local time

查看:2500
本文介绍了日历中的toInstant()以GMT(而不是本地时间)显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将日历实例转换为即时,我这样做如下

I am trying to convert a Calendar instance to instant and i am doing that as follows

    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

Fri Oct 30 17:23:40 IST 2015

2015-10-30T11:53:40.037Z

2015-10-30T11:53:40.037Z

所以,我的问题是关于日历和即时的输出的差异。即时的输出是GMT,而不是本地时间。
我还没有看到任何文档说Instant类只给出了GMT的日期。所以,我不知道为什么这种情况发生。

So, my question is about the difference in the outputs from the Calendar and the instant. The output from the instant is in GMT instead of the local time. I have not seen any documentation that says that Instant class only gives the date in GMT. So, i am not sure why this is happening.

推荐答案

回答 by Rawat是正确的。根据定义,即时始终为UTC。

The answer by Rawat is correct. An Instant is always in UTC by definition.

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

The format of the string representation generated by the toString method is standard, defined by ISO 8601.

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

The Instant class is part of the java.time framework built into Java 8 and later. The new classes in this framework supplant the old java.util.Date/.Calendar classes from the early days of Java.

避免旧类,因为它们是出了名的麻烦。不要混淆旧的和新的。诸如 toInstant 之类的转换方法仅适用于与旧代码的交互操作尚未针对新类型更新的情况。

Avoid the old classes as they are notoriously troublesome. Do not mix up the old and new. The conversion methods such as toInstant are intended only for use when interoperating with old code has not yet been updated for the new types.

要将即时调整为时区,请通过 ZoneId 对象产生 ZonedDateTime

To adjust an Instant into a time zone, specify the time zone via a ZoneId object to produce a ZonedDateTime.

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

不要被 LocalDateTime $ c> class。该类表示日期时间的模糊想法。它不会应用于任何特定时区,因此不会绑定到时间轴。

Do not be confused by the "Local" in LocalDateTime class. That class represents the vague idea of a date-time. It does not apply to any particular time zone and is therefore not tied to the timeline.

这篇关于日历中的toInstant()以GMT(而不是本地时间)显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆