Swift days between two NSDates

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

    The things built into swift are still very basic. As they should be at this early stage. But you can add your own stuff with the risk that comes with overloading operators and global domain functions. They will be local to your module though.

    let now = NSDate()
    let seventies = NSDate(timeIntervalSince1970: 0)
    
    // Standard solution still works
    let days = NSCalendar.currentCalendar().components(.CalendarUnitDay, 
               fromDate: seventies, toDate: now, options: nil).day
    
    // Flashy swift... maybe...
    func -(lhs:NSDate, rhs:NSDate) -> DateRange {
        return DateRange(startDate: rhs, endDate: lhs)
    }
    
    class DateRange {
        let startDate:NSDate
        let endDate:NSDate
        var calendar = NSCalendar.currentCalendar()
        var days: Int {
            return calendar.components(.CalendarUnitDay, 
                   fromDate: startDate, toDate: endDate, options: nil).day
        }
        var months: Int {
            return calendar.components(.CalendarUnitMonth, 
                   fromDate: startDate, toDate: endDate, options: nil).month
        }
        init(startDate:NSDate, endDate:NSDate) {
            self.startDate = startDate
            self.endDate = endDate
        }
    }
    
    // Now you can do this...
    (now - seventies).months
    (now - seventies).days
    

提交回复
热议问题