tags:

views:

570

answers:

3

Hi All,

I would like to calculate the no of days,hours,minutes between two different dates in iPhone(Objective C). Please provide any code sample to do the same.

Thanks Sandeep

+3  A: 
    NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    unsigned int uintFlags = NSYearCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit;
    NSDateComponents* differenceComponents = [gregorian components:uintFlags fromDate:firstDate toDate:secondDate options:0];

then just check properties of differenceComponents. You can find all these properties in the documentation provided with XCode

Morion
+1 for "documentation provided with Xcode" - it's also available on Apple's dev website: http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/Reference/NSCalendar.html#//apple_ref/doc/uid/TP40001451-BBCEGJCC
Tim
+3  A: 

If your dates are in NSDate objects, you can use the timeIntervalSinceDate method to find the difference as an NSTimeInterval, which will give you the difference in seconds.

You can then convert seconds to days, hours and minutes via a simple algorithm (this is off the top of my head and not tested):

minutes = seconds / 60;
seconds %= 60;
hours = minutes / 60;
minutes %= 60;
days = hours / 24;
hours %= 24;
Ferruccio
Thanks Ferruccio this was the exact thing I was looking for
sandy
A: 

Hi, I have written a comprehensive program to give the difference between two dates in C (dont know this is what you mean by Objective C). Please find the original work here.

http://www.technicalypto.com/2010/02/different-between-two-days-implemented.html

Bragboy