了解joda时间PeriodFormatter

时间:2011-01-03 15:47:39

标签: java jodatime periodformatter

我以为我明白了,但显然我没有。你能帮我把这些单元测试通过吗?

@Test
public void second() {
    assertEquals("00:00:01", OurDateTimeFormatter.format(1000));
}

@Test
public void minute() {
    assertEquals("00:01:00", OurDateTimeFormatter.format(1000 * 60));
}

@Test
public void hour() {
    assertEquals("01:00:00", OurDateTimeFormatter.format(1000 * 60 * 60));
}

@Test
public void almostMidnight() {
    final int secondsInDay = 60 * 60 * 24;
    assertEquals("23:59:59", OurDateTimeFormatter.format(1000 * (secondsInDay - 1)));
}

@Test
public void twoDaysAndAHalf() {
    final int secondsInDay = 60 * 60 * 24;
    assertEquals("12:00:00 and 2 days", OurDateTimeFormatter.format(1000 * secondsInDay * 5 / 2));
}

实际代码在这里:

public class OurDateTimeFormatter {
    public OurDateTimeFormatter() {
    }

    private static final PeriodFormatter dateFormat = new PeriodFormatterBuilder()
            .appendDays()
            .appendSuffix(" day", " days")
            .appendSeparator(" ")
            .appendHours()
            .appendSeparator(":")
            .appendMinutes().minimumPrintedDigits(2)
            .appendSeparator(":")
            .appendSeconds().minimumPrintedDigits(2)
            .toFormatter();


    public static String format(long millis) {
        return dateFormat.print(new Period(millis).normalizedStandard());
    }
}

1 个答案:

答案 0 :(得分:8)

这会修复除twoDaysAndAHalf以外的所有测试:

private static final PeriodFormatter dateFormat =
    new PeriodFormatterBuilder()
        .appendDays()
        .appendSuffix(" day", " days")
        .appendSeparator(" ")
        .printZeroIfSupported()
        .minimumPrintedDigits(2)
        .appendHours()
        .appendSeparator(":")
        .appendMinutes()
        .printZeroIfSupported()
        .minimumPrintedDigits(2)
        .appendSeparator(":")
        .appendSeconds()
        .minimumPrintedDigits(2)
        .toFormatter();

修改

也许你的twoDaysAndAHalf测试应该是这样的?

@Test
public void twoDaysAndAHalf(){
    final int secondsInDay = 60 * 60 * 24;
    assertEquals("2 days and 12:00:00",
        OurDateTimeFormatter.format(1000 * secondsInDay * 5 / 2));
}

然后使用此(稍加编辑):

private static final PeriodFormatter dateFormat =
        .appendDays()
        .appendSuffix(" day", " days")
        .appendSeparator(" and ") // thx ILMTitan
        // etc. as above

并且有效