Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 744
Abhinav Avatar asked Apr 06 '11 07:04

Abhinav


People also ask

How do I get the difference between two dates in Objective C?

NSDate *date1 = [NSDate dateWithString:@"2010-01-01 00:00:00 +0000"]; NSDate *date2 = [NSDate dateWithString:@"2010-02-03 00:00:00 +0000"]; NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1]; int numberOfDays = secondsBetween / 86400; NSLog(@"There are %d days in between the two dates.", numberOfDays);

What is NSDate?

NSDate objects encapsulate a single point in time, independent of any particular calendrical system or time zone. Date objects are immutable, representing an invariant time interval relative to an absolute reference date (00:00:00 UTC on 1 January 2001).


2 Answers

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:NSCalendarIdentifierGregorian]; NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay                                            fromDate:dateA                                              toDate:dateB                                             options:0];  NSLog(@"Difference in date components: %i/%i/%i", components.day, components.month, components.year); 
like image 173
Nick Forge Avatar answered Sep 23 '22 06:09

Nick Forge


If you subtract 12/12/2001 from 05/05/2002 what will be the date? The chronological distance between two dates can't be a date, it's alway some kind of interval. You can use timeIntervalSinceDate: to calculate the interval.

To localize you can try the following steps:

  • You can use the NSCalendar with dateFromComponents: passing in a NSDateComponents.

  • To break down a timeInterval into NSDateComponents look at How do I break down an NSTimeInterval into year, months, days, hours, minutes and seconds on iPhone?.

  • Finally use the NSDateFormatter and initWithDateFormat:allowNaturalLanguage: to get your localized string. The Date Format String Syntax shows the different placeholders.

like image 22
Nick Weaver Avatar answered Sep 24 '22 06:09

Nick Weaver