如果输入时间为零,我试图让Joda打印“ 0秒”,但是它根本什么也不打印。
以下示例仅输出一个空字符串。这里发生了什么?
PeriodFormatter hoursMinutesSeconds = new PeriodFormatterBuilder()
.appendHours().appendSuffix(" hour", " hours")
.appendSeparator(", ", " and ")
.appendMinutes()
.appendSuffix(" minute", " minutes")
.appendSeparator(" and ")
.printZeroRarelyFirst()
.appendSeconds()
.appendSuffix(" second", " seconds")
.toFormatter();
System.out.println(hoursMinutesSeconds.print(new Period(0, 0, 0, 500)));
最佳答案
您需要早期的printZeroAlways
并将您的printZeroRarelyFirst
向上移动一点,以使其能够说出0 hours
。
import org.joda.time.Period;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;
public class TestFormat {
public static void main(String[] args) {
PeriodFormatter hoursMinutesSeconds = new PeriodFormatterBuilder()
.printZeroAlways()
.appendHours().appendSuffix(" hour", " hours")
.printZeroRarelyFirst()
.appendSeparator(", ", " and ")
.appendMinutes()
.appendSuffix(" minute", " minutes")
.appendSeparator(" and ")
.appendSeconds()
.appendSuffix(" second", " seconds")
.toFormatter();
System.out.println(hoursMinutesSeconds.print(new Period(0, 0, 0, 0)));
}
}
但是,您可能更喜欢
printZeroRarelyLast
解决方案,因为上述方法始终为您提供0个小时。我更喜欢
public static void main(String[] args) {
PeriodFormatter hoursMinutesSeconds = new PeriodFormatterBuilder()
.printZeroRarelyLast()
.appendHours().appendSuffix(" hour", " hours")
.appendSeparator(", ", " and ")
.appendMinutes()
.appendSuffix(" minute", " minutes")
.appendSeparator(" and ")
.appendSeconds()
.appendSuffix(" second", " seconds")
.toFormatter();
System.out.println(hoursMinutesSeconds.print(new Period(0, 0, 0, 0)));
}