本文介绍了了解Joda时间PeriodFormatter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为我了解,但显然我不明白.您能帮我通过这些单元测试吗?

I thought I understand it, but apparently I don't. Can you help me make these unit tests pass?

@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());
    }
}

推荐答案

此修复了除twoDaysAndAHalf以外的所有测试:

This fixes all tests except 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测试应该是这样的?

perhaps your twoDaysAndAHalf test should be like this?

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

然后使用它(略作编辑):

Then use this (slightly edited):

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

它有效

这篇关于了解Joda时间PeriodFormatter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-08 09:39