【发布时间】:2017-05-06 12:59:38
【问题描述】:
我正在尝试以以下格式显示两个 DateTimes 之间的时间差:
? years, ? months, ? weeks, ? days, ? hours, ? minutes, ? seconds and ? milliseconds
我几乎可以这样显示它,但是它不显示星期。我曾尝试使用 PeriodType.standard(),但省略了几个月和几年。可以这样做吗?
这是我用来实现当前结果的代码:
private String getPeriodBetween(DateTime from, DateTime to, boolean showMilliseconds) {
Period period;
if (from.isAfter(to)) {
period = new Period(to, from);
} else {
period = new Period(from, to);
}
PeriodFormatterBuilder builder = new PeriodFormatterBuilder().appendYears()
.appendSuffix(" year, ", " years, ")
.appendMonths()
.appendSuffix(" month, ", " months, ")
.appendWeeks()
.appendSuffix(" week, ", " weeks, ")
.appendDays()
.appendSuffix(" day, ", " days, ")
.appendHours()
.appendSuffix(" hour, ", " hours, ")
.appendMinutes()
.appendSuffix(" minute, ", " minutes, ")
.appendSeconds()
.appendSuffix(" second, ", " seconds, ");
if (showMilliseconds) {
builder = builder.appendMillis().appendSuffix(" millisecond", " milliseconds");
}
return builder.toFormatter()
.print(period.normalizedStandard(PeriodType.yearMonthDayTime()))
.replaceAll("[,]\\s*$", "")
.replaceAll("(?:,\\s*)([^,]+)$", " and $1")
.replaceAll("^(?![\\s\\S])", "No difference");
}
如果我使用PeriodType.forFields(); 并指定一个包含所有必填字段的DurationFieldType 数组,则会省略年份和月份。
【问题讨论】:
标签: java datetime jodatime duration