Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a Period in Java 8 / jsr310?

Tags:

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?

like image 475
naXa Avatar asked Dec 12 '18 19:12

naXa


Video Answer


1 Answers

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); 
like image 88
Ortomala Lokni Avatar answered Oct 18 '22 08:10

Ortomala Lokni