Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift days between two NSDates

I'm wondering if there is some new and awesome possibility to get the amount of days between two NSDates in Swift / the "new" Cocoa?

E.g. like in Ruby I would do:

(end_date - start_date).to_i 
like image 247
Linus Avatar asked Jul 13 '14 13:07

Linus


People also ask

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.

How can I get tomorrow date in Swift?

You can use the following method to get any date by adding days or months or years by specifying the Calendar Component and the increment value of this component: func getSpecificDate(byAdding component: Calendar. Component, value: Int) -> Date { let noon = Calendar. current.


1 Answers

You have to consider the time difference as well. For example if you compare the dates 2015-01-01 10:00 and 2015-01-02 09:00, days between those dates will return as 0 (zero) since the difference between those dates is less than 24 hours (it's 23 hours).

If your purpose is to get the exact day number between two dates, you can work around this issue like this:

// Assuming that firstDate and secondDate are defined // ...  let calendar = NSCalendar.currentCalendar()  // Replace the hour (time) of both dates with 00:00 let date1 = calendar.startOfDayForDate(firstDate) let date2 = calendar.startOfDayForDate(secondDate)  let flags = NSCalendarUnit.Day let components = calendar.components(flags, fromDate: date1, toDate: date2, options: [])  components.day  // This will return the number of day(s) between dates 

Swift 3 and Swift 4 Version

let calendar = Calendar.current  // Replace the hour (time) of both dates with 00:00 let date1 = calendar.startOfDay(for: firstDate) let date2 = calendar.startOfDay(for: secondDate)  let components = calendar.dateComponents([.day], from: date1, to: date2) 
like image 179
Emin Bugra Saral Avatar answered Sep 28 '22 14:09

Emin Bugra Saral