Swift days between two NSDates

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

    I'm going to add my version even though this thread is a year old. My code looks like this:

        var name = txtName.stringValue // Get the users name
    
        // Get the date components from the window controls
        var dateComponents = NSDateComponents()
        dateComponents.day = txtDOBDay.integerValue
        dateComponents.month = txtDOBMonth.integerValue
        dateComponents.year = txtDOBYear.integerValue
    
        // Make a Gregorian calendar
        let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
    
        // Get the two dates we need
        var birthdate = calendar?.dateFromComponents(dateComponents)
        let currentDate = NSDate()
    
        var durationDateComponents = calendar?.components(NSCalendarUnit.CalendarUnitDay, fromDate: birthdate!, toDate: currentDate, options: nil)
    
        let numberOfDaysAlive = durationDateComponents?.day
    
        println("\(numberOfDaysAlive!)")
    
        txtGreeting.stringValue = "Hello \(name), You have been alive for \(numberOfDaysAlive!) days."
    

    I hope it helps someone.

    Cheers,

提交回复
热议问题