简体   繁体   English

从`java.time.Instant`到`java.util.Date`的转换添加了UTC偏移量

[英]Conversion from `java.time.Instant` to `java.util.Date` adds UTC offset

I seem to misunderstand java.util.Date 's conversion from and to java.time.Instance . 我似乎误解了java.util.Datejava.time.Instance的转换。 I have some legacy code I need to ineract with, and this code uses java.util.Date in its API. 我有一些遗留的代码我需要使用它,并且此代码在其API中使用java.util.Date

I am slightly confused when offsets are added in the Date API. Date API中添加偏移时,我有点困惑。 It was my understand that Date is a UTC time ("the Date class is intended to reflect coordinated universal time (UTC)"), but when I create a Date from an Instant an offset is added: 据我所知, Date是UTC时间(“Date类旨在反映协调世界时(UTC)”),但是当我从Instant创建一个Date ,会添加一个偏移量:

public class TestDateInstant {
    @Test
    public void instantdate() {
        Instant i = Instant.now();
        System.out.println(i);
        Date d = Date.from(i);
        System.out.println(d);

        assertThat(i, equalTo(d.toInstant()));
    }
}

The assertion holds, but the output on the console is: 断言成立,但控制台上的输出是:

2017-09-26T08:24:40.858Z 
Tue Sep 26 10:24:40 CEST 2017

I am wondering why Date.from uses an offset in this case. 我想知道为什么Date.from在这种情况下使用偏移量。

Date or Instant both are NOT specific to a timezone. DateInstant两者并非特定于时区。 The difference is when you print them. 不同的是你打印它们。

Instant.toString() prints in ISO-8601 representation in UTC timezone. Instant.toString()以UTC时区的ISO-8601表示形式打印。

Date.toString() prints it in your current timezone. Date.toString()打印在您当前的时区中。

That's why you see the difference. 这就是你看到差异的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM