【问题标题】:Get the difference between two dates in hours以小时为单位获取两个日期之间的差异
【发布时间】:2014-02-02 07:33:05
【问题描述】:

我正在尝试计算两个 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

那么我该怎么做呢?

【问题讨论】:

    标签: scala jodatime


    【解决方案1】:

    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
    

    Period没有工厂方法apply,你应该使用new来创建Period

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

    如果您使用nscala-time,您还可以使用to 方法获取Interval,然后将其转换为Period

    d1 to d2 toPeriod PeriodType.hours
    // org.joda.time.Period = PT672H
    
    (d1 to d2).duration.getStandardHours
    // Long = 672
    

    也可以试试sbt clean

    【讨论】:

    • d1 和 d2 不是 ReadableInstant
    • 实际上,val d1: org.joda.time.DateTime = DateTime.now() - 有效,但 val d1 = DateTime.now() 无效。类型相同 - joda DateTime。
    • @Alex:试试sbt clean,也显示你的build.sbt - 看起来你有2个不同的类同名DateTime
    猜你喜欢
    • 1970-01-01
    • 2012-06-11
    • 2013-05-14
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    • 2013-09-15
    • 1970-01-01
    • 2017-09-29
    相关资源
    最近更新 更多