Scala 以小时为单位获取两个日期之间的差异

Scala 以小时为单位获取两个日期之间的差异,scala,jodatime,Scala,Jodatime,我试图计算两个joda日期之间的时差 val d1 = getDateTime1() val d2 = getDateTime2() 以下是我所做的: # attemp1 val hours = Hours.hoursBetween(d1, d2) // error - types mismatch # attempt2 val p = Period(d1, d2, PeriodType.hours()) // error - there is such a constructor p.ge

我试图计算两个
joda
日期之间的时差

val d1 = getDateTime1()
val d2 = getDateTime2()
以下是我所做的:

# attemp1
val hours = Hours.hoursBetween(d1, d2) // error - types mismatch

# attempt2
val p = Period(d1, d2, PeriodType.hours()) // error - there is such a constructor
p.getHours

那么我该怎么做呢?

getDateTime1的类型应该是
org.joda.time.DateTime

这锅很好:

val d1: org.joda.time.DateTime = DateTime.now
val d2: org.joda.time.DateTime = DateTime.nextMonth

val hours = Hours.hoursBetween(d1, d2)
// org.joda.time.Hours = PT672H
对于
期间
,没有工厂方法
应用
,您应该使用
新建
来创建
期间

val p = new Period(d1, d2, PeriodType.hours())
// org.joda.time.Period = PT672H
d1 to d2 toPeriod PeriodType.hours
// org.joda.time.Period = PT672H

(d1 to d2).duration.getStandardHours
// Long = 672
如果正在使用,也可以使用方法
to
获取
间隔
,然后将其转换为
期间

val p = new Period(d1, d2, PeriodType.hours())
// org.joda.time.Period = PT672H
d1 to d2 toPeriod PeriodType.hours
// org.joda.time.Period = PT672H

(d1 to d2).duration.getStandardHours
// Long = 672

另外,请尝试
sbt clean

getDateTime1的类型应为
org.joda.time.DateTime

这锅很好:

val d1: org.joda.time.DateTime = DateTime.now
val d2: org.joda.time.DateTime = DateTime.nextMonth

val hours = Hours.hoursBetween(d1, d2)
// org.joda.time.Hours = PT672H
对于
期间
,没有工厂方法
应用
,您应该使用
新建
来创建
期间

val p = new Period(d1, d2, PeriodType.hours())
// org.joda.time.Period = PT672H
d1 to d2 toPeriod PeriodType.hours
// org.joda.time.Period = PT672H

(d1 to d2).duration.getStandardHours
// Long = 672
如果正在使用,也可以使用方法
to
获取
间隔
,然后将其转换为
期间

val p = new Period(d1, d2, PeriodType.hours())
// org.joda.time.Period = PT672H
d1 to d2 toPeriod PeriodType.hours
// org.joda.time.Period = PT672H

(d1 to d2).duration.getStandardHours
// Long = 672

另外,请尝试使用
sbt clean

d1和d2不可即时读取,
val d1:org.joda.time.DateTime=DateTime.now()
-可以工作,但
val d1=DateTime.now()不能。类型是相同的-joda DateTime。@Alex:尝试
sbt clean
,同时显示您的
build.sbt
-看起来您有两个同名的不同类
DateTime
。d1和d2不可即时读取,
val d1:org.joda.time.DateTime=DateTime.now()
-可以工作,但
val d1=DateTime.now()
没有。类型相同-joda DateTime。@Alex:尝试
sbt clean
,同时显示您的
版本。sbt
-看起来您有两个同名的不同类
DateTime