2017-02-18 39 views
0

我正在使用Retrofit 2来接收Json响应。我只想显示接收到的响应时间,如“03分钟前”或“1小时前”所用的时间。我已经尝试过所有我可以喜欢的日期和时间格式,但无法完成。
我试图"Time Since/Ago" Library for Android/Java,但不能这样做,因为它需要以毫秒为单位的时间,我的回应是:改造2 - 显示Json响应的已用时间

响应

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

[“Time Since/Ago”Library for Android/Java]可能的重复(http://stackoverflow.com/questions/13018550/time-since-ago-library-for-android-java) – GreyBeardedGeek

+0

@GreyBeardedGeek no它不是......上面的答案是关于什么时候以毫秒为单位,但在我的情况下它不是。 –

回答

0

我已经找到了答案。以上给出的时间是Joda时间格式iso8601。

使用乔达时库:

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

转换的时间为毫秒:

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

使用此方法将它转换成经过的时间/前:

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"; 
    } 
}