How to get the differences between two dates in iOS?

Getting difference between two dates is easy. You should know how to play between the dates.

We will be using DateFormatter class for formatting the dates.

Instances of DateFormatter create string representations of  NSDate objects, and convert textual representations of dates and times into  NSDate objects.

You can read more about it here

We will also be using Calendar structure, apple has provided beautiful documentation of it,

So let’s get started.

Open Xcode, New Playground.

Copy the below code

import UIKit
// create object of DateFormatter and Calendar
let formatter = DateFormatter()
let calendar = Calendar.current
// specify the format,
formatter.dateFormat = "dd-MM-yyyy"
// specify the start date
let startDate = "10-08-2018")
// specify the end date
let endDate = "23-09-2019")
let diff = calendar.dateComponents([.day], from: startDate!, to: endDate!)
// print the diff between the two dates