Reputation: 1091
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?
Upvotes: 4
Views: 6281
Reputation: 907
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"));
Upvotes: 5