【发布时间】:2015-03-14 21:17:50
【问题描述】:
所以我使用Joda time 并希望它只显示一个数字(我知道如何在 Joda 中处理复数,最后只是一个简单的示例)。
示例:2 years 2 months 2 weeks ago 应该只显示 2 years ago2 days 2 hours 2 minutes ago 应该只显示 2 days ago
我正在寻找一些方法来在它获得非零数字时短路附加。我已经搜索并找到了其他框架的示例,但我们已经在使用 Joda time,如果可能的话,我不想引入其他依赖项。
我现在的代码如下:
protected final String toRelativeTime(final DateTime dateTime) {
DateTime now = new DateTime();
Period period = new Period(dateTime, now);
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendYears().appendSuffix(" years")
.appendMonths().appendSuffix(" months")
.appendWeeks().appendSuffix(" weeks")
.appendDays().appendSuffix(" days")
.appendHours().appendSuffix(" hours")
.appendMinutes().appendSuffix(" minutes")
.appendSeconds().appendSuffix(" seconds")
.printZeroNever()
.toFormatter();
return formatter.print(period);
}
【问题讨论】:
-
您还搜索了哪些其他框架?我只是好奇。正如您在建议的答案中看到的那样,Joda-Time 在这个领域处理起来非常尴尬。
标签: java jodatime duration period