Swift days between two NSDates

后端 未结 27 1568
清歌不尽
清歌不尽 2020-11-27 13:30

I\'m wondering if there is some new and awesome possibility to get the amount of days between two NSDates in Swift / the \"new\" Cocoa?

E.g. like in Ruby I would do:

27条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 13:40

    Here is the answer for Swift 3 (tested for IOS 10 Beta)

    func daysBetweenDates(startDate: Date, endDate: Date) -> Int
    {
        let calendar = Calendar.current
        let components = calendar.components([.day], from: startDate, to: endDate, options: [])
        return components.day!
    }
    

    Then you can call it like this

    let pickedDate: Date = sender.date
    let NumOfDays: Int = daysBetweenDates(startDate: pickedDate, endDate: Date())
        print("Num of Days: \(NumOfDays)")
    

提交回复
热议问题