如何将 Date 对象设置为指向 java 中的不同时区

How to set Date object to point to different time zone in java

在下面的代码中,我使用日历对象将时区初始化为 GMT 并相应地获取时间,但是当我放回日期对象时,它会自动转换为我的本地时区,即 IST。

Calendar gmt = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
Date dt=gmt.getTime();

任何人都可以建议一种方法,通过它我也可以在日期对象中保留 GMT 格式。

日期class 不代表时区。它的 toString 方法使用默认的平台时区来输出一个人类可读的时间戳,在内部它只是一个 long.

its automatically converting to my local time zone i.e. IST

不,不是。 Date 对象没有时区 - 它只是一个瞬间。

如果您在 Date 上调用 toString(),您将看到 system-local 时区,因为不幸的是 Date.toString() 所做的...但是时区不是存储在Date.

中的信息的一部分

如果您想在特定时区查看 Date 的文本表示,请使用 DateFormat 并设置您要使用的时区。

java.time

其他答案正确。 toString 方法静默应用 JVM 当前的默认时区。这是旧 date-time 类 中许多糟糕的设计选择之一。转储那些旧的 类。转到 Java 8 及更高版本中内置的 java.time 框架。

Instant 是 UTC 时间线上的一个时刻。

Instant now = Instant.now();

将时区 (ZoneId) 应用于 Instant 以获得 ZonedDateTime

如果 Instant 已经在 UTC 中,我们为什么还要在 UTC 中创建一个 ZonedDateTime?因为 ZonedDateTime 让您可以灵活地格式化 date-time 值的字符串表示形式。 java.time.format 包不适用于 Instant 个对象。

ZoneId 的一个子类,ZoneOffset,有一个 UTC 常量。

ZonedDateTime zdtUtc = ZonedDateTime.ofInstant(  ZoneOffset.UTC );

调整到任何所需的时区。

ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdtKolkata = ZonedDateTime.ofInstant( instant , zoneId );

使用正确的时区名称

避免使用 3-4 个字母的时区代码。它们既不是标准化的也不是唯一的。 IST 是指 印度标准时间 还是 爱尔兰标准时间

使用standard time zone names. Most are in the pattern of continent/region. For India, Asia/Kolkata. For Ireland, Europe/Dublin.