Read the clock when you need the time
You need to read the system clock when the user presses the button, not once and for all when your app is launched. So put your call to ZonedDateTime.now()
or Calendar.getInstance()
or which means you are using for that inside the event handler that handles the button click and displays the time to the user.
The date/time object that you get from your call gets the time of when it was created and keeps that time. This is probably why you saw the time when you last updated your app. To get a new time on the next button press, you need to create a new date/time object.
java.time and ThreeTenABP
BTW the Calendar
class is poorly designed and long outdated. Here⁄s the modern way to get the current time:
DateTimeFormatter formatter = DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.MEDIUM)
.withLocale(Locale.getDefault(Locale.Category.FORMAT));
ZonedDateTime dateTime = ZonedDateTime.now(ZoneId.systemDefault());
String formattedDate = dateTime.format(formatter);
System.out.println(formattedDate);
The exact output from my snippet depends not only on the time, on the device locale too. In one instance I got the following output from running in English locale:
Dec 7, 2019 2:38:04 PM
You may create the formatter once and for all, but you need to create dateTime
every time. Instead of Calendar
and SimpleDateFormat
I am using java.time, the modern Java date and time API. It is so much nicer to work with.
To check whether we’re within some specified time period of the day, use dateTime.toLocalTime()
and compare the result to LocalTime
objects representing start and end of that period. LocalTime
has methods isBefore
and isAfter
. You need one or both of those for the comparisons.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both 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 non-Android 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.
Links