I'd like to format a Period using a pattern like YY years, MM months, DD days. The utilities in Java 8 are designed to format time but neither period, nor duration. There's a PeriodFormatter in Joda time. Does Java have similar utilities?
One solution is to simply use 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()); If your really need to use the features of DateTimeFormatter, you can use a temporary LocalDate, but this is a kind of hack that distort the semantic of 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With