我想使用像YY years, MM months, DD days这样的模式格式化一个Period。Java8中的实用程序被设计为格式化时间,但既不格式化句号,也不格式化持续时间。在Joda time中有一个PeriodFormatter。Java有类似的实用工具吗?
发布于 2018-12-13 03:30:38
一种解决方案是简单地使用String.format
import java.time.Period;
Period p = Period.of(2,5,1);
String.format("%d years, %d months, %d days", p.getYears(), p.getMonths(), p.getDays());如果你真的需要使用DateTimeFormatter的特性,你可以使用一个临时的LocalDate,但这是一种扭曲了LocalDate语义的技巧。
import java.time.Period;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
Period p = Period.of(2,5,1);
DateTimeFormatter fomatter = DateTimeFormatter.ofPattern("y 'years,' M 'months,' d 'days'");
LocalDate.of(p.getYears(), p.getMonths(), p.getDays()).format(fomatter);发布于 2018-12-15 15:57:58
不需要使用String.format()进行简单的字符串格式化。使用普通的旧字符串连接将被JVM优化:
Function<Period, String> format = p -> p.getYears() + " years, " + p.getMonths() + " months, " + p.getDays() + " days";发布于 2018-12-20 05:03:08
public static final String format(Period period){
if (period == Period.ZERO) {
return "0 days";
} else {
StringBuilder buf = new StringBuilder();
if (period.getYears() != 0) {
buf.append(period.getYears()).append(" years");
if(period.getMonths()!= 0 || period.getDays() != 0) {
buf.append(", ");
}
}
if (period.getMonths() != 0) {
buf.append(period.getMonths()).append(" months");
if(period.getDays()!= 0) {
buf.append(", ");
}
}
if (period.getDays() != 0) {
buf.append(period.getDays()).append(" days");
}
return buf.toString();
}
}https://stackoverflow.com/questions/53749850
复制相似问题