joda 期间 returns 0 个月

joda Period returns 0 months

我有 2 个 joda.DateTime,我用它来创建一个 Duration。然后 Duration 转换为 Period,虽然两个日期相隔 3 年,但 Period.getDaysPeriod.getMonthsPeriod.getYears 都是 return 0. 为什么?

来自 Scala REPL 的示例,但应该很容易 understand/convert 到 Java(如果需要我可以转换)

import org.joda.time.format.PeriodFormat
import org.joda.time.{DateTime, Period}
import org.joda.time.Duration
import org.joda.time.format.PeriodFormatterBuilder

scala> val start = DateTime.now
start: org.joda.time.DateTime = 2017-02-22T16:09:13.131Z

scala>     val end = start.plusYears(2).plusMinutes(1).plusDays(3)
end: org.joda.time.DateTime = 2019-02-25T16:10:13.131Z

scala>     val duration = new Duration(start, end)
duration: org.joda.time.Duration = PT63331260S

scala>     duration.getMillis
res0: Long = 63331260000

scala>     duration.getStandardDays
res1: Long = 733

scala>     duration.getStandardHours
res2: Long = 17592

scala>     duration.getStandardMinutes
res3: Long = 1055521

scala>     duration.getStandardSeconds
res4: Long = 63331260

scala>     val period = duration.toPeriod()
period: org.joda.time.Period = PT17592H1M

scala>     period.getDays
res5: Int = 0

scala>     period.getHours
res6: Int = 17592

scala>     period.getMinutes
res7: Int = 1

scala>     period.getSeconds
res8: Int = 0

scala>     period.getMillis
res9: Int = 0

scala> val formatter = new PeriodFormatterBuilder()
            .appendMonths().appendSuffix(" month", " months").appendSeparator(" ")
            .appendDays().appendSuffix(" day", " days").appendSeparator(" ")
            .appendHours().appendSuffix("h")
            .appendMinutes().appendSuffix("m")
            .appendSeconds().appendSuffix("s")
            .toFormatter
formatter: org.joda.time.format.PeriodFormatter = org.joda.time.format.PeriodFormatter@3096d00d

scala>     formatter.print(duration.toPeriod())
res10: String = 17592h1m

scala> PeriodFormat.getDefault.print(duration.toPeriod)
res11: String = 17592 hours and 1 minute

您正在呼叫 AbstractDuration.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.

A Duration 不“知道”它的起点和终点,因此您不能指望填充月份等可变长度值。

要获取 startend 之间的时间段,您应该只使用:

new Period(start, end)

...可能用 PeriodType 表示您想要的单位。