2016-12-13 39 views
-2

我正在處理一個需要用戶操作的項目,例如:1分鐘前,... 3小時前... 5天前。我對此很陌生,不知道如何繼續。請記住該項目是基於REST的而不是。我如何實現這一點?在Android應用程序項目中生成時間戳

回答

0

獲取以毫秒爲用戶活動時間,保存時間的地方,然後那個時候與當前時間,每次取差異,找出這個動作發生多久

你可以使用得到毫秒時間

Calendar calendar = Calendar.getInstance(); 
calendar.getTimeInMillis(); 
0

你可以得到實際的時間戳:

long timestamp = System.currentTimeMillis(); 

關於你的問題,你可以這樣做:

long eventTimestamp = System.currentTimeMillis(); 

.. 
// some other stuff happens 
.. 

//get the passed time 
long actualTimestamp = System.currentTimeMillis(); 

long timestampDifference = actualTimestamp - eventTimestamp; 

int passedSeconds = timestampDifference/1000; //get the passed time in seconds 
int passedMinutes= passedSeconds/60; //get the passed time in minutes 
0

既然你在Android你可以嘗試內置Android平臺的輔助類DateUtils。類似的東西這個未經測試的代碼:

String relativeTime = 
    DateUtils.getRelativeTimeSpanString(
    jud.getTime(), 
    System.currentTimeMillis(), 
    DateUtils.MINUTE_IN_MILLIS, 
    DateUtils.FORMAT_ABBREV_RELATIVE); 

如果你不喜歡的API風格還是沒有找到足夠的功能,或看其他問題,如缺少時區的認識,那麼你也可以下載和試用的兩個外部一個庫:

PrettyTime(超薄經典之作相對時間庫)

// your possible input 
Date jud = new Date(System.currentTimeMillis() - 3600000); 

org.ocpsoft.prettytime.PrettyTime pt = 
    new org.ocpsoft.prettytime.PrettyTime(Locale.ENGLISH); 
String relativeTime = pt.format(jud); 
System.out.println(relativeTime); // output: 1 hour ago 

或我的圖書館Time4A(大,但也更多的功能和語言):

// your possible input 
Date jud = new Date(System.currentTimeMillis() - 3600000); 

Moment moment = TemporalType.JAVA_UTIL_DATE.translate(jud); 
String relativeTime = 
    net.time4j.PrettyTime.of(Locale.US) 
     .withShortStyle() 
     .printRelativeInStdTimezone(moment); 
System.out.println(relativeTime); // output: 1 hr. ago 

其他庫不支持打印相對時間,如果有的話。