Swift days between two NSDates

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

    Swift 5

    Working, you need to set the time to be the same for both days, if you are off by seconds it will be wrong

    func daysBetween(start: Date, end: Date) -> Int {
        let start = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: start)!
        let end = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: end)!
        return Calendar.current.dateComponents([.day], from: start, to: end).day ?? 0
    }
    

提交回复
热议问题