java.time
ZonedDateTime nowInUk = ZonedDateTime.now(ZoneId.of("Europe/London"));
int hour = nowInUk.getHour();
int minutes = nowInUk.getMinute();
int seconds = nowInUk.getSecond();
int day = nowInUk.getDayOfMonth();
Month month = nowInUk.getMonth();
int year = nowInUk.getYear();
System.out.println("hour = " + hour + ", minutes = " + minutes + ", seconds = " + seconds
+ ", day = " + day + ", month = " + month + ", year = " + year);
When I ran this snippet just now, it printed:
hour = 3, minutes = 41, seconds = 15, day = 5, month = OCTOBER, year =
2018
ZonedDateTime
largely replaces the outdated Calendar
class.
What went wrong in your code?
Time zone ID for UK time is Europe/London
. In your code you used UTC
, which is something else and wll give you a different result, at least sometimes. UK time coincides with UTC some of the year in some years, but not at this time of year this year. So you got a time that was one hour earlier than UK time.
Also c1.get(Calendar.HOUR)
gives you the hour within AM or PM from 1 through 12, which I don’t think was what you intended.
Question: Can I use java.time
on Android?
Yes, java.time
works nicely on Android devices. It just requires at least Java 6.
- In Java 8 and later and on new Android devices (from API level 26, I’m told) the new API comes built-in.
- In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310, where the modern API was first described).
- On (older) Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. Make sure you import the date and time classes from package
org.threeten.bp
and subpackages.
Links