java - PeriodFormatter 不显示日期

标签 java datetime jodatime periodformatter

我正在使用 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() );

最佳答案

这是因为你转换了DurationPeriod用方法 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.

如果没有开始日期(或结束日期),则无法正确计算期间保险,因为有些日子可能是 24h23h(由于 DST)

你应该使用方法Duration::toPeriodFrom方法代替
例如。

Duration duration = new Duration(date1, date2);  
// ...  
formatter.print( duration.toPeriodFrom(date1));

关于java - PeriodFormatter 不显示日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26291271/

相关文章:

使用rest在neo4j中运行密码查询的java示例

python - 用 pandas 计算每天的值总数

java - 将日期与 jodatime 进行比较

java - for 循环 onclicklistener

Java面向对象编程和多态性

计算午夜数的Java代码(00 :00:00) in a date range

java - Joda 时间库 getdays 给出错误结果

java - 如何轻松将 Joda YearMonth 转换为 LocalDateTime

java - 当从变量传递时,我们如何转义名称中包含空格的文件夹名称?

r - 在 timeDate 包中循环假期