gpt4 book ai didi

java - joda 期间返回 0 个月

转载 作者:行者123 更新时间:2023-12-01 20:55:40 25 4
gpt4 key购买 nike

我有 2 个 joda.DateTime,我用它来创建 Duration。然后将 Duration 转换为 Period,尽管两个日期相差 3 年,但 Period.getDays, Period. getMonthsPeriod.getYears 都返回 0。为什么?

来自 Scala REPL 的示例,但应该易于理解/转换为 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.

Duration 并不“知道”它的起点和终点,因此您不能期望填充诸如月份之类的可变长度值。

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

new Period(start, end)

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

关于java - joda 期间返回 0 个月,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42396756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com