0

I am using Retrofit 2 to recieve Json response. I just want to show the received response time as elapsed time like "03 min ago" or "1 hour ago". I have tried everything I could like Date and Time Format but was not able to do it.
I tried "Time Since/Ago" Library for Android/Java but couldn't do it because It required the time in milliseconds and my response is:

Response

"publishedAt": "2017-02-17T12:44:01Z"  
Community
  • 1
  • 1
Omer Danish
  • 101
  • 1
  • 2
  • 13
  • Possible duplicate of ["Time Since/Ago" Library for Android/Java](http://stackoverflow.com/questions/13018550/time-since-ago-library-for-android-java) – GreyBeardedGeek Feb 18 '17 at 16:03
  • @GreyBeardedGeek no Its not... the above answer is about when u get the time in milliseconds but in my case its not. – Omer Danish Feb 18 '17 at 18:58

1 Answers1

0

I have found the answer. The above given time is in Joda Time Format iso8601.

Use Joda Time Library:

compile 'joda-time:joda-time:2.9.7'  

Convert the time into milliseconds:

long millisSinceEpoch = new DateTime(yourtime).getMillis();
String time = getTimeAgo(millisSinceEpoch, context);  

Use this method to convert it into Elapsed Time Since/Ago:

public static String getTimeAgo(long time, Context ctx) {
    if (time < 1000000000000L) {
        // if timestamp given in seconds, convert to millis
        time *= 1000;
    }
    long now = System.currentTimeMillis();
    if (time > now || time <= 0) {
        return null;
    }
    // TODO: localize
    final long diff = now - time;
    if (diff < MINUTE_MILLIS) {
        return "just now";
    } else if (diff < 2 * MINUTE_MILLIS) {
        return "a minute ago";
    } else if (diff < 50 * MINUTE_MILLIS) {
        return diff / MINUTE_MILLIS + " minutes ago";
    } else if (diff < 90 * MINUTE_MILLIS) {
        return "an hour ago";
    } else if (diff < 24 * HOUR_MILLIS) {
        return diff / HOUR_MILLIS + " hours ago";
    } else if (diff < 48 * HOUR_MILLIS) {
        return "yesterday";
    } else {
        return diff / DAY_MILLIS + " days ago";
    }
}
Omer Danish
  • 101
  • 1
  • 2
  • 13