java.time and ThreeTenABP
Don’t mingle with raw offsets. Java knows the offset for Berlin better than you. And consider not using Calendar
. That class has a number of design problems and is considered long outdated.
ZonedDateTime zdtBerlin = ZonedDateTime.now(ZoneId.of("Europe/Berlin"));
System.out.println("Zeit in Berlin: " + zdtBerlin);
When I ran this snippet just now, I got this output:
Zeit in Berlin: 2019-02-08T19:23:00.275+01:00[Europe/Berlin]
As the name says, a ZonedDateTime
has a time zone in it. In this case Europe/Berlin. It’s the modern replacement for GregorianCalendar
(the most common concrete subclass of the abstract Calendar
class).
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
- In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
- In Java 6 and 7 get the ThreeTen Backport, the backport of the modern 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.
What went wrong in your code?
Snippet 1-: You are setting the Calendar
’s time to an hour into the future. You are not setting the time zone.
Snippet 2-: First SimpleTimeZone
hasn’t got a no-arg constructor, so new SimpleTimeZone()
won’t work. Next, its setRawOffset
expects an offset in milliseconds. If rawOffset
is 1, you are setting an offset of 1 millisecond.
Links