java.time and ThreeTen Backport
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss z", Locale.US);
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("America/Los_Angeles"));
String d = zdt.format(formatter);
System.out.println(d);
zdt = zdt.withZoneSameLocal(ZoneId.of("America/New_York"));
String d1 = zdt.format(formatter);
System.out.println(d1);
Output when I ran the code just now:
2018.07.10 04:30:20 PDT
2018.07.10 04:30:20 EDT
The ZonedDateTime
class that you mentioned in a comment has your desired conversion built in, in its withZoneSameLocal
method. This returns the same wall clock time in the specified time zone.
As of now, we use Java 7. We have not upgraded our infra to java 8…
No big problem. java.time
and its ZonedDateTime
work nicely on Java 7. They just require at least Java 6.
- In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
- In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
- On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links