Swift days between two NSDates

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

    I translated my Objective-C answer

    let start = "2010-09-01"
    let end = "2010-09-05"
    
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    
    let startDate:NSDate = dateFormatter.dateFromString(start)
    let endDate:NSDate = dateFormatter.dateFromString(end)
    
    let cal = NSCalendar.currentCalendar()
    
    
    let unit:NSCalendarUnit = .Day
    
    let components = cal.components(unit, fromDate: startDate, toDate: endDate, options: nil)
    
    
    println(components)
    

    result

    
         Day: 4
    

    The hardest part was that the autocompletion insists fromDate and toDate would be NSDate?, but indeed they must be NSDate! as shown in the reference.

    I don't see how a good solution with an operator would look like, as you want to specify the unit differently in each case. You could return the time interval, but than won't you gain much.

提交回复
热议问题