java – 我的PeriodFormatter表现不像我期望的那样 – 我做错了什么?

前端之家收集整理的这篇文章主要介绍了java – 我的PeriodFormatter表现不像我期望的那样 – 我做错了什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在使用Joda Time的PeriodFormatter时遇到了麻烦.我想要一个人报告日,小时,分钟和秒钟,但我的尝试似乎在几周之内.我应该做些什么呢?
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;

public class Problems {

    public static void main(String[] args) {

        PeriodFormatter formatter = new PeriodFormatterBuilder()
            .printZeroNever()
            .appendDays()
            .appendSuffix(" day"," days")
            .appendSeparator(",")
            .appendHours()
            .appendSuffix(" hour"," hours")
            .appendSeparator(",")
            .appendMinutes()
            .appendSuffix(" minute"," minutes")
            .appendSeparator(",")
            .appendSeconds()
            .appendSuffix(" second"," seconds")
            .toFormatter();

        DateTime now = new DateTime();
        DateTime justUnderAWeekAgo = now.minusDays(7).plusMinutes(1);
        DateTime justOverAWeekAgo = now.minusDays(7).minusMinutes(1);
        System.out.println(now);
        System.out.println(justUnderAWeekAgo);
        System.out.println(justOverAWeekAgo);
        // I am happy with the following:
        System.out.println(
            formatter.print(new Period(justUnderAWeekAgo,now)));
        // But not with this (outputs "1 minute" but I want "7 days,1 minute"):
        System.out.println(
            formatter.print(new Period(justOverAWeekAgo,now)));
    }
}

编辑:我想我可以看到为什么这不起作用 – 即格式化程序只打印Period的各种值,并且由于Periods存储了一个值数周,我的问题期间的天数值确实为0.但我仍然需要这样做的好方法……

解决方法

在您的情况下,问题是您不要求您的PeriodFormatter显示周.

两种可能性:

解决方案1:显示周数:

PeriodFormatter formatter = new PeriodFormatterBuilder()
        .printZeroNever()
        .appendWeeks()
        .appendSuffix(" week"," weeks")
        .appendSeparator(",")
        .appendDays()
        .appendSuffix(" day"," days")
        .appendSeparator(",")
        .appendHours()
        .appendSuffix(" hour"," hours")
        .appendSeparator(",")
        .appendMinutes()
        .appendSuffix(" minute"," minutes")
        .appendSeparator(",")
        .appendSeconds()
        .appendSuffix(" second"," seconds")
        .toFormatter();

您的示例中的第二个输出将是:

1 week,1 minute

解决方案2:仅显示日期,因此您必须使用PeriodType.yearMonthDayTime():

new Period(justUndeAWeekAgo,now,PeriodType.yearMonthDayTime());

使用第二个解决方案,您可以保持PeriodFormatter现在的状态.您的示例中的第二个输出将是:

7 days,1 minute

猜你在找的Java相关文章