Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 - find number of calendar days between two dates

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?

like image 838
Vinod Vishwanath Avatar asked Oct 16 '16 21:10

Vinod Vishwanath


People also ask

How do I extract the number of days between two dates?

To find the number of days between these two dates, you can enter “=B2-B1” (without the quotes into cell B3). Once you hit enter, Excel will automatically calculate the number of days between the two dates entered. Note that Excel recognizes leap years.

How do I compare two dates in Swift?

let date1 = Date() let date2 = Date(). addingTimeInterval(100) if date1 == date2 { ... } else if date1 > date2 { ... } else if date1 < date2 { ... } if i want to ignore time. e.g. 2019-05-14 12:08:14 +0000 == 2019-05-14 should return true.

How can I get the difference 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.

How do you subtract dates in Swift?

To subtract hours from a date in swift we need to create a date first. Once that date is created we have to subtract hours from that, though swift does not provide a way to subtract date or time, but it provides us a way to add date or date component in negative value.


2 Answers

In Swift 5 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 

Note: As pointed out in the comments, this solution measures the 24h periods and therefore requires at least 24h between dateA and dateB.

like image 121
flo_23 Avatar answered Sep 22 '22 05:09

flo_23


Turns out this is much simpler to do in Swift 3:

extension Date {          func interval(ofComponent comp: Calendar.Component, fromDate date: Date) -> Int {          let currentCalendar = Calendar.current          guard let start = currentCalendar.ordinality(of: comp, in: .era, for: date) else { return 0 }         guard let end = currentCalendar.ordinality(of: comp, in: .era, for: self) else { return 0 }          return end - start     } } 

Edit

Comparing the ordinality of the two dates should be within the same era instead of the same year, since naturally the two dates may fall in different years.

Usage

let yesterday = Date(timeInterval: -86400, since: Date()) let tomorrow = Date(timeInterval: 86400, since: Date())   let diff = tomorrow.interval(ofComponent: .day, fromDate: yesterday) // return 2 
like image 44
Vinod Vishwanath Avatar answered Sep 21 '22 05:09

Vinod Vishwanath