gpt4 book ai didi

java - joda time periodFormatter 不打印年份

转载 作者:行者123 更新时间:2023-12-01 21:18:13 24 4
gpt4 key购买 nike

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

 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。 Duration 只是几毫秒...考虑其中的年数有点麻烦,因为一年要么是 365 天,要么是 366 天(甚至这取决于日历系统)。这就是为什么 toPeriod method you're calling明确表示:

Only precise fields in the period type will be used. Thus, only the hour, minute, second and millisecond fields on the period will be used. The year, month, week and day fields will not be populated.

那么您调用normalizedStandard(PeriodType)其中包括:

The days field and below will be normalized as necessary, however this will not overflow into the months field. Thus a period of 1 year 15 months will normalize to 2 years 3 months. But a period of 1 month 40 days will remain as 1 month 40 days.

不要从 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());

关于java - joda time periodFormatter 不打印年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39588030/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com