2017-03-16 56 views
1

我想从JodaTime的持续时间类获取格式化的字符串。从JodaTime持续时间格式化的字符串

Duration duration = new Duration(durationInSecond * 1000); 
PeriodFormatter formatter = new PeriodFormatterBuilder() 
       .appendDays() 
       .appendSuffix(" days, ") 
       .appendHours() 
       .appendSuffix(" hours, ") 
       .appendMinutes() 
       .appendSuffix(" minutes and ") 
       .appendSeconds() 
       .appendSuffix(" seconds") 
       .toFormatter(); 
String formattedString = formatter.print(duration.toPeriod()); 

formattedString值应该为

65天,3小时,5分20秒

但它是

1563小时,5分钟, 20秒

1563小时为65天3小时,但格式化程序不是以这种方式打印的。

我在这里错过了什么?

回答

1

你可以使用一个PeriodType随着Period.normalizedStandard(org.joda.time.PeriodType)来指定哪些领域你有兴趣。

在你的情况PeriodType.dayTime()似乎是适当的。

Duration duration = new Duration(durationInSecond * 1000); 
PeriodFormatter formatter = new PeriodFormatterBuilder() 
     .appendDays() 
     .appendSuffix(" days, ") 
     .appendHours() 
     .appendSuffix(" hours, ") 
     .appendMinutes() 
     .appendSuffix(" minutes, ") 
     .appendSeconds() 
     .appendSuffix(" seconds") 
     .toFormatter(); 

Period period = duration.toPeriod(); 
Period dayTimePeriod = period.normalizedStandard(PeriodType.dayTime()); 
String formattedString = formatter.print(dayTimePeriod); 

System.out.println(formattedString); 
+0

非常感谢。 –

1

我发现使用

PeriodFormat.getDefault() 

有助于无需做使用PeriodFormatterBuilder所有额外的工作和创建自己的创造PeriodFormatter。它给出了相同的结果。

相关问题