0

I have a problem in converting java.time.Instant to java.util.Date:

System.out.println(item.getStart()); // getStart returns instant
System.out.println(Date.from(item.getStart()));

gives output:

2017-08-29T00:00:00Z
Tue Aug 29 02:00:00 CEST 2017

Why in date time is 02:00:00? And how to do convertion with time 00:00:00

Ole V.V.
  • 65,573
  • 11
  • 96
  • 117
  • 1
    Both correspond to the same instant. But `Instant` is printed in UTC and `Date` is printed in the JVM default timezone. You don't convert the `Date` object because [it has no format](https://codeblog.jonskeet.uk/2017/04/23/all-about-java-util-date). If you want to convert to a `String`, though, take a look at https://stackoverflow.com/q/4216745/7605325 –  Sep 14 '17 at 17:00
  • 1
    What you have observed, is the expected and correct behaviour. Your `Date` holds the same point in time. `System.out.println()` implicitly calls `Date.toString()`, which in turn converts the time to a string in Central European time zone, producing the output you see. – Ole V.V. Sep 14 '17 at 17:30
  • 1
    “And how to do convertion with time 00:00:00?” You already got a `Date` with time 00:00:00 UTC. Don’t let yourself fool by the output from `toString()`. – Ole V.V. Sep 14 '17 at 17:35
  • 2
    As Ole V.V. commented, the `Date::toString` lies. The method applies the JVM’s current default time zone, implying the zone is assigned to the `Date` object when actually a `Date` is always in UTC. One of many reasons to avoid this terrible old class. Use only the java.time classes instead. – Basil Bourque Sep 15 '17 at 03:22
  • 1
    As Hugo commented, **midnight UTC *is* the same moment as 2 AM in central Europe**. If someone in Reykjavík Iceland watching their clock strike midnight says to their friend on the telephone sitting in Paris France, "Wow, look at the time", the Parisian responds "Mais oui, 2 AM". – Basil Bourque Sep 15 '17 at 03:24

1 Answers1

3

In 2017-08-29T00:00:00Z the Z means Zulu, which means UTC+0. So it describtes exactly the same moment in time as Tue Aug 29 02:00:00 CEST 2017 which is UTC+2

It gets printed as CEST because the default implementation of the toString() method is using the default time zone.

You could try using Java8 LocalDate instead. It hasn’t got any time-of-day information.

How to do the conversion you can see here: https://stackoverflow.com/a/35187046/1199731

Ole V.V.
  • 65,573
  • 11
  • 96
  • 117
d0x
  • 9,378
  • 14
  • 58
  • 93