Abhinav Abhinav - 1 year ago 62
iOS Question

Difference between two NSDate objects -- Result also a NSDate

I have two NSDate objects and I want the difference between the two and the result should again be a NSDate object. Any idea how to achieve this?

Here, I am trying to address a unique problem where I have to find out the elapsed time and then localize the elapsed time. I can localize it if I have the elapsed time in NSDate object. So thought of creating a NSDate object which has its time component same as time interval between the two dates so that I could use NSDateFormatter to localize it.

Answer Source

NSDate represents an instance in time, so it doesn't make sense to represent an interval of time as an NSDate. What you want is NSDateComponents:

NSDate *dateA;
NSDate *dateB;

NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay

NSLog(@"Difference in date components: %i/%i/%i", components.day, components.month, components.year);