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?
Use:
If any one want to do it more specifically follow Below Steps
1.Add this Date Extension
2.Define it in globally
3.Call this Method in viewDidLoad or where ever you want
4.Usage
Works like Charm You can Use every separate string to your UI Side, Enjoy
In Swift 4 there is a simple one-liner to get the number of days (or any other DateComponent) between two dates:
if you want to print the number of days as well as days list between two calendar dates, used below simple code;
// Variable Declaration:
// function Defination:
// To call above function:
// Enjoy coding...!
If someone would need to display all time units e.g "hours minutes seconds" not just "hours". Let's say the time difference between two dates is 1hour 59minutes 20seconds. This function will display "1h 59m 20s".
Here is my code:
Function Definition: