Get the difference between two dates in hours

牧云@^-^@ 提交于 2019-12-10 00:03:19

问题


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.



来源:https://stackoverflow.com/questions/21508168/get-the-difference-between-two-dates-in-hours

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!