如何用Joda-Time計算從現在開始的經過時間?我需要計算從特定日期到現在所用的時間,并以與StackOverflow問題相同的格式顯示它,即:15s ago2min ago2hours ago2days ago25th Dec 08您知道如何使用Java Joda-Time庫實現它嗎?是否有一個已經實現它的輔助方法,或者我應該自己編寫算法?
3 回答

慕俠2389804
TA貢獻1719條經驗 獲得超6個贊
要使用JodaTime計算經過的時間,請使用Period
。要格式化所需人類表示中的已用時間,請使用PeriodFormatter
您可以構建的表達式PeriodFormatterBuilder
。
這是一個啟動示例:
DateTime myBirthDate = new DateTime(1978, 3, 26, 12, 35, 0, 0);DateTime now = new DateTime();Period period = new Period(myBirthDate, now);PeriodFormatter formatter = new PeriodFormatterBuilder() .appendSeconds().appendSuffix(" seconds ago\n") .appendMinutes().appendSuffix(" minutes ago\n") .appendHours().appendSuffix(" hours ago\n") .appendDays().appendSuffix(" days ago\n") .appendWeeks().appendSuffix(" weeks ago\n") .appendMonths().appendSuffix(" months ago\n") .appendYears().appendSuffix(" years ago\n") .printZeroNever() .toFormatter();String elapsed = formatter.print(period);System.out.println(elapsed);
這打印到現在
3秒前51分鐘前7小時前6天前10個月前31年前
(咳嗽,老了,咳嗽)你看我已經考慮了數月和數年,并將其配置為在零值時省略值。

幕布斯6054654
TA貢獻1876條經驗 獲得超7個贊
使用PrettyTime進行簡單的經過時間。
我嘗試了HumanTime,因為@sfussenegger回答并使用了JodaTime,Period
但是我發現人類可讀時間最簡單,最干凈的方法是PrettyTime庫。
這里有一些帶輸入和輸出的簡單示例:
五分鐘前
DateTime fiveMinutesAgo = DateTime.now().minusMinutes( 5 );new PrettyTime().format( fiveMinutesAgo.toDate() );// Outputs: "5 minutes ago"
不久前
DateTime birthday = new DateTime(1978, 3, 26, 12, 35, 0, 0);new PrettyTime().format( birthday.toDate() );// Outputs: "4 decades ago"
小心:我已經嘗試過使用圖書館更精確的功能,但它會產生一些奇怪的結果,所以要小心使用它,并在非危及生命的項目中使用它。

DIEA
TA貢獻1820條經驗 獲得超3個贊
您可以使用PeriodFormatter執行此操作,但您不必像在其他答案中那樣努力創建自己的PeriodFormatBuilder 。如果它適合您的情況,您可以使用默認格式化程序:
Period period = new Period(startDate, endDate);System.out.println(PeriodFormat.getDefault().print(period))
(就類似的問題給出了這個答案的提示,我為了發現而交叉發布)
添加回答
舉報
0/150
提交
取消