Swift days between two NSDates

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

    Erin's method updated to Swift 3, This shows days from today (disregarding time of day)

    func daysBetweenDates( endDate: Date) -> Int 
        let calendar: Calendar = Calendar.current 
        let date1 = calendar.startOfDay(for: Date()) 
        let date2 = calendar.startOfDay(for: secondDate) 
        return calendar.dateComponents([.day], from: date1, to: date2).day! 
    }
    

提交回复
热议问题