How to convert timestamp into human readable time string (for example "one minute ago") in Java

342 Views Asked by At

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: Example

Is that possible in Java in some way? Thank You.

2

There are 2 best solutions below

3
deHaar On BEST ANSWER

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.

2
Eritrean On

If you want to use a third party library, you might want to take a look at PrettyTime Library

Using PrettyTime your code could look as simple as:

String calculateTimeAgoWithPrettyTime(final Instant pastTime) {
    PrettyTime prettyTime = new PrettyTime();
    return prettyTime.format(pastTime);
}