我以为我明白了,但显然我不明白。你能帮我通过这些单元测试吗?
@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
之外的所有测试:
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
它有效