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.
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.
java. util. Date has no specific time zone, although its value is most commonly thought of in relation to UTC.
Java8 Instant. now() gives the current time already formatted in UTC.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With