Swift days between two NSDates

后端 未结 27 1450
清歌不尽
清歌不尽 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:41

    Here is my answer for Swift 3:

    func daysBetweenDates(startDate: NSDate, endDate: NSDate, inTimeZone timeZone: TimeZone? = nil) -> Int {
        var calendar = Calendar.current
        if let timeZone = timeZone {
            calendar.timeZone = timeZone
        }
        let dateComponents = calendar.dateComponents([.day], from: startDate.startOfDay, to: endDate.startOfDay)
        return dateComponents.day!
    }
    

提交回复
热议问题