我想格式化 Period
使用 YY 年、MM 月、DD 日
之类的模式。 Java 8 中的实用程序旨在格式化时间,但既不是周期也不是持续时间。有一个PeriodFormatter
在乔达时代。 Java 有类似的实用程序吗?
最佳答案
一种解决方案是简单地使用 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
语义的 hack .
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);
关于java - 如何在 Java 8/jsr310 中格式化句点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53749850/