jodatime - PeriodFormatter:后缀仅适用于 day/days
jodatime - PeriodFormatter: suffix only for day/days
我只需要显示 day/days 的后缀,我该如何实现?
它不起作用:
java.lang.IllegalStateException: No field to apply suffix to..
private PeriodFormatter getDayTextFormatter() {
return new PeriodFormatterBuilder()
.printZeroNever()
.appendSuffix("day", "days")
.toFormatter();
}
我认为这不可能。根据JodaTime's javadoc,appendSuffix
方法如果没有字段追加后缀会抛出异常:
Throws: IllegalStateException - if no field exists to append to
所以我相信JodaTime这次帮不了你了。虽然,你可以这样做:
private String suffix(Period p) {
int days = p.getDays();
if (days <= 0) {
return "";
}
return days == 1 ? "day" : "days";
}
使用此代码,以下内容:
System.out.println(suffix(Period.days(1)));
System.out.println(suffix(Period.days(2)));
System.out.println(suffix(new Period()));
产生输出:
day
days
// and a line with an empty string
我只需要显示 day/days 的后缀,我该如何实现? 它不起作用:
java.lang.IllegalStateException: No field to apply suffix to..
private PeriodFormatter getDayTextFormatter() {
return new PeriodFormatterBuilder()
.printZeroNever()
.appendSuffix("day", "days")
.toFormatter();
}
我认为这不可能。根据JodaTime's javadoc,appendSuffix
方法如果没有字段追加后缀会抛出异常:
Throws: IllegalStateException - if no field exists to append to
所以我相信JodaTime这次帮不了你了。虽然,你可以这样做:
private String suffix(Period p) {
int days = p.getDays();
if (days <= 0) {
return "";
}
return days == 1 ? "day" : "days";
}
使用此代码,以下内容:
System.out.println(suffix(Period.days(1)));
System.out.println(suffix(Period.days(2)));
System.out.println(suffix(new Period()));
产生输出:
day
days
// and a line with an empty string