开发者

Understanding joda time PeriodFormatter

开发者 https://www.devze.com 2023-02-02 09:59 出处:网络
I thought I understand it, but apparently I don\'t. Can you help me make these unit tests pass? @Test public void second() {

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() {
    f开发者_JS百科inal 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));
}

Where the actual code is here:

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


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

EDIT:

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

and it works

0

精彩评论

暂无评论...
验证码 换一张
取 消