I am trying to create a chat application in android studio.
I have a timestamp, say this
1694603269045
Now I want to convert this timestamp into human readable way like one minute ago
or one hour ago
. I will is into my storyView
mode where a user will be able to see when his friends uploaded a story/status.
I need this as String
, like
one minute ago
so that I can use it in a TextView
. Is that possible?
I tried to find some solutions but most of them are related to javascript where I need it in Java.
The String
needs to be like this:
Is that possible in Java in some way? Thank You.
You can create an Instant
from your timestamp and calculate the Duration
between it and Instant.now()
.
public static void main(String[] args) {
// your timestamp
long timestamp = 1694603269045L;
// convert to an Instant
Instant then = Instant.ofEpochMilli(timestamp);
// get "now"
Instant now = Instant.now();
// calulate the Duration
Duration duration = Duration.between(then, now);
// print the minutes part
System.out.println(duration.toMinutesPart() + " minutes ago");
}
This just printed
47 minutes ago
You will have to check which values (hours, minutes, seconds and so on) are actually zero if you want to switch from minutes to hours when minutes are 0, but hours aren't, for example. This would print 0 minutes ago
in 13 minutes and you may want to cover situations like that.