How can I calculate the difference between two dates? How can I calculate the difference between two dates? swift swift

How can I calculate the difference between two dates?


NSDate *date1 = [NSDate dateWithString:@"2010-01-01 00:00:00 +0000"];NSDate *date2 = [NSDate dateWithString:@"2010-02-03 00:00:00 +0000"];NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];int numberOfDays = secondsBetween / 86400;NSLog(@"There are %d days in between the two dates.", numberOfDays);

EDIT:

Remember, NSDate objects represent exact moments of time, they do not have any associated time-zone information. When you convert a string to a date using e.g. an NSDateFormatter, the NSDateFormatter converts the time from the configured timezone. Therefore, the number of seconds between two NSDate objects will always be time-zone-agnostic.

Furthermore, this documentation specifies that Cocoa's implementation of time does not account for leap seconds, so if you require such accuracy, you will need to roll your own implementation.


You may want to use something like this:

NSDateComponents *components;NSInteger days;components = [[NSCalendar currentCalendar] components: NSDayCalendarUnit         fromDate: startDate toDate: endDate options: 0];days = [components day];

I believe this method accounts for situations such as dates that span a change in daylight savings.


NSTimeInterval diff = [date2 timeIntervalSinceDate:date1]; // in seconds

where date1 and date2 are NSDate's.

Also, note the definition of NSTimeInterval:

typedef double NSTimeInterval;