改造2 - 显示Json响应的经过时间

时间:2017-02-18 14:38:34

标签: android retrofit2

我正在使用Retrofit 2来接收Json的回应。我只是想把收到的响应时间显示为经过的时间,比如" 03分钟前"或者" 1小时前"。我已经尝试了所有我喜欢的日期和时间格式,但却无法做到 我试过了"Time Since/Ago" Library for Android/Java但是无法做到,因为它需要时间,以毫秒为单位,我的回答是:

响应

"publishedAt": "2017-02-17T12:44:01Z"  

1 个答案:

答案 0 :(得分:0)

我找到了答案。上面给出的时间是Joda Time Format iso8601。

使用Joda时间库:

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

将时间转换为毫秒:

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

使用此方法将其转换为自/ 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";
    }
}