Get the difference between two dates in hours

2020-07-30 00:17发布

问题:

I'm trying to calculate the hour difference between two joda dates.

val d1 = getDateTime1()
val d2 = getDateTime2()

Here is what I did:

# 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

So how do I do this?

回答1:

The type of getDateTime1 should be org.joda.time.DateTime.

This woks fine:

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

There is no factory method apply for Period, you should use new to create Period:

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

If you are using nscala-time you could also use method to to get Interval and than convert it to Period:

d1 to d2 toPeriod PeriodType.hours
// org.joda.time.Period = PT672H

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

Also try sbt clean.