joda time PeriodFormatter不打印年份

时间:2016-09-20 07:22:29

标签: java jodatime

我有一个格式化程序如下:

 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

那么岁月在哪里?

1 个答案:

答案 0 :(得分:3)

这里的根本问题是您使用Duration开始,IMO。 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());
相关问题