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 t
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);
You can calculate the time interval between two dates using NSDate
's timeIntervalSinceDate:
, but it doesn't make any sense for you to represent a time interval as a date.
There is a easy way by using -compare: in NSDate:
NSDate *dateA = [NSDate dateWithTimeIntervalSinceNow:100];
NSDate *dateB = [NSDate dateWithTimeIntervalSinceNow:200];
NSDate *myDate = [NSDate dateWithTimeIntervalSinceNow:150];
NSArray *dateArray = [NSArray arrayWithObjects:dateA, dateB, myDate, nil];
NSArray *sortedArray = [dateArray sortedArrayUsingSelector:@selector(compare:)];
if ([myDate isEqualToDate:[sortedArray objectAtIndex:1]])
NSLog(@"myDatea between dateA and dateB");
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.
From NSDate
class reference, you have instance methods to do these -
isEqualToDate:
timeIntervalSinceDate: