首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >joda time PeriodFormatter不打印年份

joda time PeriodFormatter不打印年份
EN

Stack Overflow用户
提问于 2016-09-20 07:22:28
回答 1查看 306关注 0票数 0

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

代码语言:javascript
复制
 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();

并按以下方式使用:

代码语言:javascript
复制
        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);

产出如下:

代码语言:javascript
复制
2274 days 13 hours 59 minutes 39 seconds

那么这些年在哪里呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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“创建。

代码语言:javascript
复制
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());
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39588030

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档