Difference between 2 dates in weeks and days using swift 3 and xcode 8

FormulaOne picture FormulaOne · Feb 17, 2017 · Viewed 28k times · Source

I am trying to calculate the difference between 2 dates (one is the current date and the other from datepicker) in weeks and days then displaying the result on a label, that's what i have done so far, i appreciate the help of more experienced developers here!

let EDD = datePicker.date
let now = NSDate()

let formatter = DateComponentsFormatter()
formatter.unitsStyle = .short
formatter.allowedUnits = [.day]
formatter.maximumUnitCount = 2   

let string = formatter.string (from: now as Date, to: EDD)

label.text = string

Answer

Ashley Mills picture Ashley Mills · Feb 17, 2017

You can use Calendar's dateComponents(_:from:to:) to find the difference between 2 dates to your desired units.

Example:

let dateRangeStart = Date()
let dateRangeEnd = Date().addingTimeInterval(12345678)
let components = Calendar.current.dateComponents([.weekOfYear, .month], from: dateRangeStart, to: dateRangeEnd)

print(dateRangeStart)
print(dateRangeEnd)
print("difference is \(components.month ?? 0) months and \(components.weekOfYear ?? 0) weeks")


> 2017-02-17 10:05:19 +0000
> 2017-07-10 07:26:37 +0000
> difference is 4 months and 3 weeks

let months = components.month ?? 0
let weeks = components.weekOfYear ?? 0