【问题标题】:Understanding joda time PeriodFormatter了解 joda time PeriodFormatter
【发布时间】:2011-01-03 15:47:38
【问题描述】:

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

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

【问题讨论】:

    标签: java jodatime periodformatter


    【解决方案1】:

    这修复了除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
    

    它可以工作

    【讨论】:

    • 是的,我知道我会在这个测试中进行很长时间的测试 :) 我会试一试并检查一下。顺便说一句,对不起我的懒惰,这是一个 rtfm 类型的问题。
    • and 不应该是分隔符的一部分而不是后缀的一部分吗?
    • 像魅力一样工作,谢谢。我喜欢 SODD(堆栈溢出驱动开发)
    • @ILMTitan 可能。今天之前我从未听说过 PeriodFormatters :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-08
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    相关资源
    最近更新 更多