Stefan Nestorov Stefan Nestorov - 1 month ago 45x
Swift Question

Swift 3 Calendar.range - migrate function

I am not sure how to migrate this function correctly to swift 3.

extension Date {

func numberOfDaysUntilDateTime(toDateTime: NSDate, calendar:NSCalendar) -> Int {

var fromDate: NSDate?, toDate: NSDate?

calendar.rangeOfUnit(.Day, startDate: &fromDate, interval: nil, forDate: self)
calendar.rangeOfUnit(.Day, startDate: &toDate, interval: nil, forDate: toDateTime)

let difference = calendar.components(.Day, fromDate: fromDate!, toDate: toDate!, options: [])





See for example this answer How to get the 'n' weekday of a Date on how to use rangeOfUnit in Swift 3.

However, there is an easier method to get the start of the day for a date which translates directly to Swift 3:

extension Date {
    func numberOfDaysUntilDateTime(toDateTime: Date, calendar: Calendar) -> Int {
        let fromDate = calendar.startOfDay(for: self)
        let toDate = calendar.startOfDay(for: toDateTime)
        let difference = calendar.dateComponents([.day], from: fromDate, to: toDate)