Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PeriodFormatter not showing days

I am using a PeriodFormatter to return a string showing the time until an event. The code below keeps creating strings like 1146 hours 39 minutes instead of x days y hours z minutes. Any ideas?

Thanks, Nathan

   PeriodFormatter formatter = new PeriodFormatterBuilder()
                .printZeroNever()
                .appendDays()
                .appendSuffix( "d " )
                .appendHours()
                .appendSuffix( "h " )
                .appendMinutes()
                .appendSuffix( "m " )
                .toFormatter();
        return formatter.print( duration.toPeriod() );
like image 865
Nath5 Avatar asked Oct 10 '14 02:10

Nath5


1 Answers

This is because you convert Duration to Period with method Duratoin::toPeriod
This is described in Joda-time documentation:

public Period toPeriod() Converts this duration to a Period instance using the standard period type and the ISO chronology. Only precise fields in the period type will be used. Thus, only the hour, minute, second and millisecond fields on the period will be used. The year, month, week and day fields will not be populated.

Period insance cann't be calculated properly without start date (or end date), because some days can be 24h or 23h (due to DST)

You shoud use method Duration::toPeriodFrom method instead
E.g.

Duration duration = new Duration(date1, date2);  
// ...  
formatter.print( duration.toPeriodFrom(date1));
like image 129
Ilya Avatar answered Oct 11 '22 14:10

Ilya