3 回答

TA貢獻1719條經(jīng)驗 獲得超6個贊
要使用JodaTime計算經(jīng)過的時間,請使用Period
。要格式化所需人類表示中的已用時間,請使用PeriodFormatter
您可以構(gòu)建的表達式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);
這打印到現(xiàn)在
3秒前51分鐘前7小時前6天前10個月前31年前
(咳嗽,老了,咳嗽)你看我已經(jīng)考慮了數(shù)月和數(shù)年,并將其配置為在零值時省略值。

TA貢獻1876條經(jīng)驗 獲得超7個贊
使用PrettyTime進行簡單的經(jīng)過時間。
我嘗試了HumanTime,因為@sfussenegger回答并使用了JodaTime,Period
但是我發(fā)現(xiàn)人類可讀時間最簡單,最干凈的方法是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"
小心:我已經(jīng)嘗試過使用圖書館更精確的功能,但它會產(chǎn)生一些奇怪的結(jié)果,所以要小心使用它,并在非危及生命的項目中使用它。

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