2017-03-16 32 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。它給出了相同的結果。

相關問題