来自 JodaTime 持续时间的格式化字符串

Formatted string from JodaTime duration

我正在尝试从 JodaTime 的持续时间中获取格式化字符串 class。

Duration duration = new Duration(durationInSecond * 1000);
PeriodFormatter formatter = new PeriodFormatterBuilder()
                .appendDays()
                .appendSuffix(" days, ")
                .appendHours()
                .appendSuffix(" hours, ")
                .appendMinutes()
                .appendSuffix(" minutes and ")
                .appendSeconds()
                .appendSuffix(" seconds")
                .toFormatter();
String formattedString = formatter.print(duration.toPeriod());

formattedString 的值应该是

65 days, 3 hours, 5 minutes and 20 seconds

但是

1563 hours, 5 minutes, 20 seconds

1563 小时是 65 天零 3 小时,但格式化程序未以这种方式打印。

我在这里缺少什么?

您可以使用 PeriodTypePeriod.normalizedStandard(org.joda.time.PeriodType) 来指定您感兴趣的字段。

在你的情况下PeriodType.dayTime()似乎是合适的。

Duration duration = new Duration(durationInSecond * 1000);
PeriodFormatter formatter = new PeriodFormatterBuilder()
        .appendDays()
        .appendSuffix(" days, ")
        .appendHours()
        .appendSuffix(" hours, ")
        .appendMinutes()
        .appendSuffix(" minutes, ")
        .appendSeconds()
        .appendSuffix(" seconds")
        .toFormatter();

Period period = duration.toPeriod();
Period dayTimePeriod = period.normalizedStandard(PeriodType.dayTime());
String formattedString = formatter.print(dayTimePeriod);

System.out.println(formattedString);

我发现使用 PeriodFormat.getDefault() 有助于创建 PeriodFormatter,而无需使用 PeriodFormatterBuilder 和创建您自己的 PeriodFormatterBuilder 来完成所有额外工作。它给出了相同的结果。

PeriodFormat.wordBasedPeriodFormat.getDefault() 相同,但接受 Locale 参数。

import java.util.Locale
import org.joda.time.Duration
import org.joda.time.PeriodType
import org.joda.time.format.PeriodFormat


PeriodFormat.wordBased(
    Locale("en"))
    .print(
        Duration(1653419081151L)
            .toPeriod()
            .normalizedStandard(
//                PeriodType.standard() // 2733 weeks, 5 days, 19 hours, 4 minutes, 41 seconds and 151 milliseconds
//                PeriodType.dayTime() // 19136 days, 19 hours, 4 minutes, 41 seconds and 151 milliseconds
//                PeriodType.weeks() // 2733 weeks
                PeriodType.days() // 19136 days
            )
    )

将为您提供首选语言的正确输出。

或使用自己的 PeriodType:

normalizedStandard(
            PeriodType.forFields(
                arrayOf(
                    DurationFieldType.years(),
                    DurationFieldType.months(),
                    DurationFieldType.days(),
                    DurationFieldType.hours(),
                    DurationFieldType.minutes()
                )
            )