2017-02-18 37 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"; 
    } 
}