我有一个格式化程序如下:
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那么这些年在哪里呢?
发布于 2016-09-20 07:29:36
这里的根本问题是你首先使用Duration,海事组织。一个Duration只是几毫秒.考虑年数有点麻烦,因为一年要么是365天,要么是366天(甚至取决于日历系统)。这就是为什么 method you're calling明确指出:
将只使用期间类型中的精确字段。因此,将只使用周期上的小时、分钟、秒和毫秒字段。年、月、周和日的字段将不会被填充。
然后调用normalizedStandard(PeriodType),其中包括:
days字段和以下区域将在必要时标准化,但是这不会溢出到月份字段中。因此,为期1年,15个月将正常化为2年,3个月。但1个月40天为1个月40天。
与其从Duration创建句点,不如直接从DateTime和"now“创建。
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());https://stackoverflow.com/questions/39588030
复制相似问题