0

I need to convert a LocalDateTime to UTC date, here is my code

    LocalDateTime ldt = LocalDateTime.now();
    System.out.println("Local date Time " +ldt);

    ZonedDateTime ldtZoned = ldt.atZone(ZoneId.systemDefault());

    ZonedDateTime utcZoned = ldtZoned.withZoneSameInstant(ZoneOffset.UTC);

    System.out.println("UTC Zone"+utcZoned);

    Instant i = utcZoned.toInstant();
    System.out.println("Instant "+i);
    Date out = Date.from(i);
    System.out.println("date from Instant "+ out);

The output comes as

Local date Time 2019-05-08T16:23:53.109
UTC Zone2019-05-08T22:23:53.109Z
Instant 2019-05-08T22:23:53.109Z
date from Instant Wed May 08 16:23:53 MDT 2019

Till 3rd statement all is good. But when we get Date object from Instant it converts the Date object back to Local Time.

How can we get Date object as UTC from LocaldateTime??

Tatha
  • 1,253
  • 2
  • 24
  • 42
  • Though not exactly same. Have a look at this https://stackoverflow.com/questions/308683/how-can-i-get-the-current-date-and-time-in-utc-or-gmt-in-java – Abhijith Nagarajan May 08 '19 at 22:30
  • No need to to call `withZoneSameInstant(ZoneOffset.UTC)`. The result will be the same without that call. --- See answer to [How can I get the current date and time in UTC or GMT in Java?](https://stackoverflow.com/a/308689/5221149) for why the result is correct, and it's just you who are confused because you're printing the `Date` value incorrectly, i.e. the fact that `Date` objects are *always* in UTC, but `toString()` formats it in the default time zone. If you want to print the `Date` in UTC, don't use `toString()`. which is what your code is implicitly doing. – Andreas May 08 '19 at 22:52
  • There is no such thing as a `java.util.Date` in UTC. A `Date` hasn’t got a UTC offset or time zone. See for example [DateFormat parse - not return date in UTC](https://stackoverflow.com/questions/47307909/dateformat-parse-not-return-date-in-utc). – Ole V.V. May 09 '19 at 05:12

0 Answers0