Swift days between two NSDates

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

    You could use the following extension:

    public extension Date {
        func daysTo(_ date: Date) -> Int? {
            let calendar = Calendar.current
    
            // Replace the hour (time) of both dates with 00:00
            let date1 = calendar.startOfDay(for: self)
            let date2 = calendar.startOfDay(for: date)
    
            let components = calendar.dateComponents([.day], from: date1, to: date2)
            return components.day  // This will return the number of day(s) between dates
        }
    }
    

    Then, you can call it like this:

    startDate.daysTo(endDate)
    

提交回复
热议问题