Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an Accurate Time Difference Between two NSDate?

Is there any way to find out an accurate difference between two NSDate?

I have found solutions but they aren't accurate enough. I need to take into account daylight saving, the fact that different months have a different number of days, etc.

A simple calculation such as /60/60/24 etc. to work out minutes, hours and days doesn't take them into account.

Lets say I need to work out the difference between the time right now ([NSDate date]) and December 25th 10:22PM (date chosen by user using date picker [datePicker date]) just as an example, how would I do this?
Knowing the exact time difference isn't the key, so long as I have an accurate difference of days, months and years, it will do.

like image 908
Josh Kahane Avatar asked Dec 05 '11 15:12

Josh Kahane


2 Answers

From Apple's Date & Time Programming Guide:

Listing 12 Getting the difference between two dates

NSDate *startDate = ...;
NSDate *endDate = ...;

NSCalendar *gregorian = [[NSCalendar alloc]
                 initWithCalendarIdentifier:NSGregorianCalendar];

NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;

NSDateComponents *components = [gregorian components:unitFlags
                                          fromDate:startDate
                                          toDate:endDate options:0];
NSInteger months = [components month];
NSInteger days = [components day];
like image 179
Darek Rossman Avatar answered Oct 03 '22 21:10

Darek Rossman


NSDate is completely independent of Timezone. Daylight saving doesn't even come into the picture for NSDate. Only when you convert NSDate into a human readable format (MM/DD/YY, HH:MM:SS format or the like), does Time Zone come into picture.

Make sure that you take into account correct timezone, day-light saving setting when you create NSDate(s). Subsequently, the method, [date1 timeIntervalSinceDate:date2] should always give you accurate time difference.

like image 20
Sanjay Chaudhry Avatar answered Oct 03 '22 22:10

Sanjay Chaudhry