Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between two NSDates

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.

like image 250
Minkle Garg Avatar asked Aug 22 '11 13:08

Minkle Garg


2 Answers

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 :)

like image 104
martin Avatar answered Nov 15 '22 19:11

martin


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]

like image 44
kviksilver Avatar answered Nov 15 '22 17:11

kviksilver