如何使用 Joda-Time 计算从现在起经过的时间? [英] How to calculate elapsed time from now with Joda-Time?

查看:24
本文介绍了如何使用 Joda-Time 计算从现在起经过的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算从一个特定日期到现在的时间,并以与 StackOverflow 问题相同的格式显示,即:

15 秒前2 分钟前2小时前2天前08 年 12 月 25 日

您知道如何使用 Java Joda-Time 库来实现它?是否有已经实现它的辅助方法,还是我应该自己编写算法?

解决方案

要使用 JodaTime 计算经过的时间,请使用 Period.要在所需的人类表示中格式化经过的时间,请使用 PeriodFormatter 可以通过 PeriodFormatterBuilder.

这是一个启动示例:

DateTime myBirthDate = new DateTime(1978, 3, 26, 12, 35, 0, 0);DateTime now = new DateTime();期间期间=新期间(myBirthDate,现在);PeriodFormatter 格式化程序 = new PeriodFormatterBuilder().appendSeconds().appendSuffix("秒前
").appendMinutes().appendSuffix("分钟前
").appendHours().appendSuffix("小时前
").appendDays().appendSuffix("几天前
").appendWeeks().appendSuffix("几周前
").appendMonths().appendSuffix("几个月前
").appendYears().appendSuffix("年前
").printZeroNever().toFormatter();String elapsed = formatter.print(period);System.out.println(elapsed);

现在打印出来

<前>3 秒前51 分钟前7 小时前6 天前10 个月前31 年前

(咳嗽,老,咳嗽) 你看,我也考虑了几个月和几年,并将其配置为忽略零时的值.

I need to calculate the time elapsed from one specific date till now and display it with the same format as StackOverflow questions, i.e.:

15s ago
2min ago
2hours ago
2days ago
25th Dec 08

Do you know how to achieve it with the Java Joda-Time library? Is there a helper method out there that already implements it, or should I write the algorithm myself?

解决方案

To calculate the elapsed time with JodaTime, use Period. To format the elapsed time in the desired human representation, use PeriodFormatter which you can build by PeriodFormatterBuilder.

Here's a kickoff example:

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
")
    .appendMinutes().appendSuffix(" minutes ago
")
    .appendHours().appendSuffix(" hours ago
")
    .appendDays().appendSuffix(" days ago
")
    .appendWeeks().appendSuffix(" weeks ago
")
    .appendMonths().appendSuffix(" months ago
")
    .appendYears().appendSuffix(" years ago
")
    .printZeroNever()
    .toFormatter();

String elapsed = formatter.print(period);
System.out.println(elapsed);

This prints by now

3 seconds ago
51 minutes ago
7 hours ago
6 days ago
10 months ago
31 years ago

(Cough, old, cough) You see that I've taken months and years into account as well and configured it to omit the values when those are zero.

这篇关于如何使用 Joda-Time 计算从现在起经过的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆