16

I am taking two NSDates by using date time picker. Now I want to count the number of days between these two NSDates. How can I find the difference between two NSDates.

please give me some solution.

Thanks alot.

EmptyStack
  • 51,274
  • 23
  • 147
  • 178
Minkle Garg
  • 723
  • 3
  • 9
  • 35
  • possible duplicate of [Number of days between two NSDates](http://stackoverflow.com/questions/4739483/number-of-days-between-two-nsdates) – jscs Aug 22 '11 at 17:29

3 Answers3

57

Here's a little gem for you - with more than just days:

// Assuming you have fistDate and secondDate

unsigned int unitFlags = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitDay | NSCalendarUnitMonth;

NSDateComponents *conversionInfo = [currCalendar components:unitFlags fromDate:fistDate   toDate:secondDate  options:0];

int months = [conversionInfo month];
int days = [conversionInfo day];
int hours = [conversionInfo hour];
int minutes = [conversionInfo minute];

This is very helpful - especially when formatting string such as:

[NSString stringWithFormat:@"%d months , %d days, %d hours, %d min", months, days, hours, minutes];

Happy Coding :)

martin
  • 2,493
  • 1
  • 20
  • 13
  • @Dave DeLong Yeah it's a pity people are content to play the hard way with floats and ints for such matters. – martin Aug 22 '11 at 17:27
  • And? what should we do with firstDate and secondDate? – Gargo Oct 23 '14 at 19:29
  • 3
    NSHourCalendarUnit was changed to NSCalendarUnitHour. Same with mins, days, months. Guess that Apple engineer was on crack that day. – GeneCode Sep 01 '16 at 06:15
25

NSDate reference is a great little document: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html

- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate

is what you are looking for if you want time interval difference.

For days (as not every day has same number of minutes, hours) you want to see Martins answer below and use NSDateComponents with [NSCalendar currentCalendar]

kviksilver
  • 3,824
  • 1
  • 26
  • 27
2

Here's a Swift implementation (I use this all the time while debugging things like network requests and JSON parsing):

let date1 = NSDate()

// do some long running task

let date2 = NSDate()
print(date2.timeIntervalSinceDate(date1))

// you can also do this in one line, of course:
print(NSDate().timeIntervalSinceDate(date1))
worthbak
  • 335
  • 3
  • 8