Swift 3 - 查找两个日期之间的日历天数 [英] Swift 3 - find number of calendar days between two dates

查看:46
本文介绍了Swift 3 - 查找两个日期之间的日历天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Swift 2.3 中的做法是:

The way I did this in Swift 2.3 was:

let currentDate         = NSDate()
let currentCalendar     = NSCalendar.currentCalendar()

var startDate : NSDate?
var endDate   : NSDate?

// The following two lines set the `startDate` and `endDate` to the start of the day

currentCalendar.rangeOfUnit(.Day, startDate: &startDate, interval: nil, forDate: currentDate)
currentCalendar.rangeOfUnit(.Day, startDate: &endDate, interval: nil, forDate: self)

let intervalComps = currentCalendar.components([.Day], fromDate: startDate!, toDate: endDate!, options: [])

print(intervalComps.day)

现在这一切都随着 Swift 3 改变了.我要么使用 NSCalendarNSDateSwift 3 的做法.

Now this has all changed with Swift 3. I have to either use NSCalendar and NSDate by constantly type casting with as, or find the Swift 3 way of doing it.

在 Swift 3 中正确的做法是什么?

What's the right way to do it in Swift 3?

推荐答案

事实证明,这在 Swift 3 中要简单得多:

Turns out this is much simpler to do in Swift 3:

extension Date {    

    func interval(ofComponent comp: Calendar.Component, fromDate date: Date) -> Int {

        let currentCalendar = Calendar.current

        guard let start = currentCalendar.ordinality(of: comp, in: .era, for: date) else { return 0 }
        guard let end = currentCalendar.ordinality(of: comp, in: .era, for: self) else { return 0 }

        return end - start
    }
}

编辑

比较两个日期的序数应该在同一个era,而不是同一个year,因为自然两个日期可能落在不同的年份.

Comparing the ordinality of the two dates should be within the same era instead of the same year, since naturally the two dates may fall in different years.

使用

let yesterday = Date(timeInterval: -86400, since: Date())
let tomorrow = Date(timeInterval: 86400, since: Date())


let diff = tomorrow.interval(ofComponent: .day, fromDate: yesterday)
// return 2

这篇关于Swift 3 - 查找两个日期之间的日历天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆