Swift 3 - find number of calendar days between two dates

Vinod Vishwanath picture Vinod Vishwanath · Oct 16, 2016 · Viewed 55.1k times · Source

The way I did this in Swift 2.3 was:

let currentDate         = NSDate()
let currentCalendar     = NSCalendar.currentCalendar()

var startDate : NSDate?
var endDate   : NSDate?

// The following two lines set the `startDate` and `endDate` to the start of the day

currentCalendar.rangeOfUnit(.Day, startDate: &startDate, interval: nil, forDate: currentDate)
currentCalendar.rangeOfUnit(.Day, startDate: &endDate, interval: nil, forDate: self)

let intervalComps = currentCalendar.components([.Day], fromDate: startDate!, toDate: endDate!, options: [])

print(intervalComps.day)

Now this has all changed with Swift 3. I have to either use NSCalendar and NSDate by constantly type casting with as, or find the Swift 3 way of doing it.

What's the right way to do it in Swift 3?

Answer

flo_23 picture flo_23 · Oct 16, 2017

In Swift 4 there is a simple one-liner to get the number of days (or any other DateComponent) between two dates:

let diffInDays = Calendar.current.dateComponents([.day], from: dateA, to: dateB).day