Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. I have some legacy code I need to ineract with, and this code uses java.util.Date in its API.

I am slightly confused when offsets are added in the 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:

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.

like image 619
Jens Avatar asked Sep 26 '17 08:09

Jens


People also ask

Is Java time instant UTC?

In java8, I would use the Instant class which is already in UTC and is convenient to work with. No, an Instant is not at local time. An Instant by definition is in UTC.

Is Java Util date UTC?

java. util. Date has no specific time zone, although its value is most commonly thought of in relation to UTC.

Is Instant NOW () UTC?

Java8 Instant. now() gives the current time already formatted in UTC.

Does Java Util date have timezone?

util. Date objects do not contain any timezone information by themselves - you cannot set the timezone on a Date object. The only thing that a Date object contains is a number of milliseconds since the "epoch" - 1 January 1970, 00:00:00 UTC.


1 Answers

Date or Instant both are NOT specific to a timezone. The difference is when you print them.

Instant.toString() prints in ISO-8601 representation in UTC timezone.

Date.toString() prints it in your current timezone.

That's why you see the difference.

like image 66
Codebender Avatar answered Sep 24 '22 23:09

Codebender