Barebones solution:
long remainingMillis = countdownEnds.getTime() - System.currentTimeMillis();
long remainingMinutes = TimeUnit.MILLISECONDS.toMinutes(remainingMillis);
String countdownEndsString = String.format("%d minutes", remainingMinutes);
For a nicer solution use java.time
, the modern Java date and time API, for the calculation of the minutes:
long remainingMinutes = ChronoUnit.MINUTES.between(
Instant.now(), DateTimeUtils.toInstant(countdownEnds));
In this case also see if you can get rid of the use of Date
completely since that class is long outdated, and all the functionality and more is in java.time
. In the last snippet I am using the ThreeTen Backport (see explanation and links below) and its DateTimeUtils
class. For anyone reading along and using Java 8 or later and still not having got rid of the Date
class, the conversion is built into that class, so it is slightly simpler yet:
long remainingMinutes
= ChronoUnit.MINUTES.between(Instant.now(), countdownEnds.toInstant());
You may also want to look into the Duration
class of java.time
.
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, 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
- Oracle tutorial: Date Time explaining how to use
java.time
. - Java Specification Request (JSR) 310, where
java.time
was first described. - ThreeTen Backport project, the backport of
java.time
to Java 6 and 7 (ThreeTen for JSR-310). - ThreeTenABP, Android edition of ThreeTen Backport
- Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
solved show remaining minutes instead of hours