我正在使用 PeriodFormatter 返回一个字符串,显示事件发生前的时间。下面的代码不断创建像 1146 小时 39 分钟这样的字符串,而不是 x 天 y 小时 z 分钟。有什么想法吗?
谢谢, 弥敦道
PeriodFormatter formatter = new PeriodFormatterBuilder()
.printZeroNever()
.appendDays()
.appendSuffix( "d " )
.appendHours()
.appendSuffix( "h " )
.appendMinutes()
.appendSuffix( "m " )
.toFormatter();
return formatter.print( duration.toPeriod() );
最佳答案
这是因为你转换了Duration至 Period用方法 Duratoin::toPeriod
这在 Joda-time 文档中有描述:
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.
如果没有开始日期(或结束日期),则无法正确计算期间保险,因为有些日子可能是 24h 或 23h(由于 DST)
你应该使用方法Duration::toPeriodFrom方法代替
例如。
Duration duration = new Duration(date1, date2);
// ...
formatter.print( duration.toPeriodFrom(date1));
关于java - PeriodFormatter 不显示日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26291271/