4

Every solution I have found for this "serializes" the date/time value to a string and then parses it again into the desired time zone. That seems an inefficient way to do it. I am using java SE 8 and it seems there is better support for dealing with time zones with the new classes (though I am admittedly not well versed in the java SDK). I played around with them and the following, rather simple solution seems to work just fine but without a string representation of the date/time as the go-between.

ZonedDateTime localDateTime = ZonedDateTime.now();
System.out.println(localDateTime);
ZonedDateTime utcDateTime = ZonedDateTime.ofInstant(
  localDateTime.toInstant(), 
  ZoneOffset.UTC
);
System.out.println(utcDateTime);

Results:

2015-01-07T11:02:43.368-05:00[America/New_York]
2015-01-07T16:02:43.368Z

Am I oversimplifying?

Mike
  • 1,031
  • 14
  • 36
  • Seems fine to me. Can you give examples of those "serializing" solutions you found? – Thomas Jan 07 '15 at 16:12
  • the solutions you are referring to are most likely pre-jdk8 solutions. jdk8 got a brand new date/time api (all of `java.time` is new). – jtahlborn Jan 07 '15 at 16:15
  • Here's one solution which was pre-jdk8 I suppose: http://stackoverflow.com/questions/19375357/java-convert-gmt-utc-to-local-time-doesnt-work-as-expected – Mike Jan 07 '15 at 18:24

1 Answers1

4

Your approach works, but there is a cleaner method, see: https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html#withZoneSameInstant-java.time.ZoneId-

Something like this should work:

localDateTime.withZoneSameInstant(ZoneId.of("UTC"));
MikeN
  • 887
  • 5
  • 18