简体   繁体   English

使用SwiftDate的日期之间的小时数

[英]Hours between dates with SwiftDate

What's the easiest way to get number of hours between 2 dates with SwiftDate lib? 使用SwiftDate lib获取两个日期之间的小时数的最简单方法是什么?

In this case hours could be days / minutes or whatever I'll need next time. 在这种情况下,时间可能是数天/分钟,或者下一次我需要的时间。

I see I can probably do (date1 - date2) / 60 * 60 but that just does not feel right. 我看到我可能可以做到(date1 - date2) / 60 * 60但这感觉并不对。

Calendar can do that: Calendar可以做到这一点:

let calendar = Calendar.current
let components = calendar.dateComponents([.hour], from: date1, to: date2)
let hours = components.hour!

or as one-liner: 或单线:

let hours = Calendar.current.dateComponents([.hour], from: date1, to: date2).hour!

or as Date extension: 或作为Date扩展名:

extension Date {

    func hoursSince(date: Date) -> Int
    {
        return Calendar.current.dateComponents([.hour], from: date, to: self).hour!
    }
}

在SwiftDate中,您可以轻松完成

(date1 - date2).in(.hour)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM