将 ZoneId 应用于 Java 中的 Date 对象

Apply ZoneId to Date object in Java

我有以下日期对象 Wed Nov 01 00:00:00 GMT 2017。这显然是格林威治标准时间,但是,我想认为它处于不同的时区。

例如,我想考虑以下时区 US/Mountain 中的上述日期,然后我想将其转换为 UTC,结果为 Wed Nov 01 07:00:00 UTC.

我试图找到一种方法来更改日期的时区,同时保留时间,但失败了。

谢谢

利用java时间API,您可以:

  1. 将字符串解析为 ZonedDateTime
  2. 使用zonedDateTime.withZoneSameLocalzonedDateTime.withZoneSameInstant转换结果

像这样:

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z uuuu");

ZonedDateTime gmt = ZonedDateTime.parse("Wed Nov 01 00:00:00 GMT 2017", fmt);
ZonedDateTime mountain = gmt.withZoneSameLocal(ZoneId.of("US/Mountain"));
ZonedDateTime utc = mountain.withZoneSameInstant(ZoneOffset.UTC);

System.out.println(utc.format(fmt));

顺便说一句,输出:Wed Nov 01 06:00:00 Z 2017(DST 仅在 11 月 3 日生效)。

我从你的评论中了解到你有一个 java.util.Date 实例。它打印为(例如)Wed Nov 01 00:00:00 GMT 2017。这就是它的 toString 方法产生的结果。 Date 中没有时区。通常 Date.toString() 获取 JVM 的时区设置并在该时区中呈现日期。看来您是 运行 GMT 时区?您可以在 this popular blog entry: All about java.util.Date.

中阅读更多内容

如果可以,请避免DateThe modern Java date and time API known as java.time or JSR-310 is so much nicer to work with, both in general and not least for time zone magic like yours. Then use .

对于这个答案,我假设您从一些遗留的 API 中得到了一个 Date,您无法更改(或现在无法负担更改)。我仍然推荐现代 API 来实现您想要的改变。以下片段的输出我在代码中作为注释给出。

    System.out.println(oldFashionedDateObject); // Wed Nov 01 00:00:00 GMT 2017
    // first thing, convert the Date to an instance of a modern class, Instant
    Instant pointInTime = oldFashionedDateObject.toInstant();
    // convert to same hour and minute in US/Mountain and then back into UTC
    ZonedDateTime convertedDateTime = pointInTime.atOffset(ZoneOffset.UTC)
            .atZoneSimilarLocal(ZoneId.of("US/Mountain"))
            .withZoneSameInstant(ZoneOffset.UTC);
    System.out.println(convertedDateTime); // 2017-11-01T06:00Z

    // only assuming you absolutely and indispensably need an old-fashioned Date object back
    oldFashionedDateObject = Date.from(convertedDateTime.toInstant());
    System.out.println(oldFashionedDateObject); // Wed Nov 01 06:00:00 GMT 2017

作为亚述,我得到了Wed Nov 01 06:00:00。根据 Current Local Time in Denver, Colorado, USA 夏令时 (DST) 于今年 11 月 5 日结束。