java.time
import java.time.Instant;
import java.time.temporal.ChronoUnit;
fun timeSince(dateStr: String): String {
val diffHours = ChronoUnit.HOURS.between(Instant.parse(dateStr), Instant.now())
return "%d h ago".format(diffHours)
}
Let’s try it out:
fun main() {
println(timeSince("2019-01-22T12:43:01Z"))
}
This just printed:
236 h ago
I am using java.time, the modern Java date and time API. Compared to the old classes Date
and not least SimpleDateFormat
I find it so much nicer to work with. The method above will throw a DateTimeParseException
if the string passed to it is not in ISO 8601 format. For most purposes this is probably better than returning 0 h ago
. The method is tolerant to presence and absence of (up to 9) decimals on the seconds, so accepts for example 2019-01-22T12:43:01.654321Z
.
Don’t we need a formatter? No. I am taking advantage of the fact that your string is in ISO 8601 format, the format that the modern date and time classes parse (and also print) as their default.
I wish I could use ChronoUnit
and Instant
Edit:
I wish I could use ChronoUnit & Instant, but it requires a min V26 of Android. My current min is 23.
java.time works nicely on older Android devices too. 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?
I see two bugs in the code in your question:
- As 竹杖芒鞋轻胜马 already pointed out in this answer, your format expects 4 parts between
T
and Z
, separated by colons, but your string has only three parts there. With SimpleDateFormat
using two SS
for fraction of second is also wrong since uppercase S
is for milliseconds, so only three SSS
would make sense (by contrast, with the modern DateTimeFormatter
S
is for fraction of second, so any number (up to 9 SSSSSSSSS
) makes sense).
- You are treating the
Z
in the string as a literal. It’s a UTC offset of zero and needs to be parsed as such, or you will get an incorrect time (on the vast majority of JVMs).
Links