Reputation: 6335
I am creating date like this:
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
Date.from(now.toInstant());
I need Date object have current time in utc, but when I print date it gives me my local time and not utc time. I also tried with:
OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
Date date = Date.from(now.toInstant());
But when I print Date again time is not in utc. Am I doing something wrong when creating Date object. Why above 2 approaches not give me Date that have current time in utc.
Upvotes: 0
Views: 1141
Reputation: 86281
Two points:
Date
class, in particular when you are already using classes from java.time
, the modern Java date and time API.Date
object hasn’t got and cannot have a time zone in it.If you need your offset, you need to hold on to your OffsetDateTime
(or ZonedDateTime
) object:
OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
System.out.println(now);
On my computer this just printed
2017-11-21T11:53:11.519Z
The Z
in the end indicates Zulu time zone, another name for UTC (you may also informally think of it as Zero offset from UTC).
If you would like a more human-readable format, you are right, use a formatter:
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL);
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
System.out.println(now.format(formatter));
Depending on your locale and the time, this prints something like
Tuesday, November 21, 2017 11:53:11 AM Z
Again the Z
means Zulu time zone, UTC.
Date
is not going to help youA Date
is just a point in time. So is the Instant
that you use for initializing the date. None of them has got a time zone or offset. The difference here is their toString
methods: The Instant
is always printed in UTC, the Date
usually (always?) in the JVM’s default time zone. The latter confuses many into thinking the Date
has a time zone when it hasn’t. See All about java.util.Date.
As I have demonstrated, a formatter may put a time zone or offset into a string when formatting the date-time. This does not in any way modify the date-time object, whether OffsetDateTime
, ZonedDateTime
, Instant
or Date
. The long outdated DateFormat
class may do the same when formatting a Date
. It cannot and will not set a time zone in the Date
object since (and I repeat) a Date
object cannot have a time zone in it.
Long story short, you have no need for the outdated Date
class that I can see.
Upvotes: 3