乔达时间PeriodFormatter不打印多年
问题描述:
我有一个格式如下:乔达时间PeriodFormatter不打印多年
private static PeriodFormatter formatter = new PeriodFormatterBuilder()
.printZeroNever()
.appendYears().appendSuffix(" years ")
.appendMonths().appendSuffix(" months ")
.appendWeeks().appendSuffix(" weeks ")
.appendDays().appendSuffix(" days ")
.appendHours().appendSuffix(" hours ")
.appendMinutes().appendSuffix(" minutes ")
.appendSeconds().appendSuffix(" seconds")
.toFormatter();
和如下使用它:
DateTime dt = DateTime.parse("2010-06-30T01:20");
Duration duration = new Duration(dt.toInstant().getMillis(), System.currentTimeMillis());
Period period = duration.toPeriod().normalizedStandard(PeriodType.yearMonthDayTime());
formatter.print(period);
输出为:
2274 days 13 hours 59 minutes 39 seconds
那么,是几年?
答
这里的根本问题是您使用Duration
来开始IMO。 A Duration
只是毫秒数......考虑到年数,有些麻烦,因为一年365或366天(甚至取决于日历系统)。这就是为什么toPeriod
method you're calling明确表示:
只有期间类型中的精确字段将被使用。因此,只能使用该时段的小时,分钟,秒和毫秒字段。年,月,周和日期字段将不会填充。
然后你打电话normalizedStandard(PeriodType)
其中包括:
的日子场和下面将被标准化为必要的,但是这不会溢出到几个月领域。因此,1年15个月的时间将正常化为2年3个月。但1个月40天的期限将保留为1个月40天。
不像从一个Duration
创建期间,直接从DateTime
创建它和“现在”,例如
DateTime dt = DateTime.parse("2010-06-30T01:20");
DateTime now = DateTime.now(); // Ideally use a clock abstraction for testability
Period period = new Period(dt, now, PeriodType.yearMonthDayTime());