Subtracting two NSDate objects [duplicate] Subtracting two NSDate objects [duplicate] json json

Subtracting two NSDate objects [duplicate]


Create two NSDate objects from the strings using NSDate's -dateWithString:, then get the difference of the two NSdate objects using

NSTimeInterval diff = [date2 timeIntervalSinceDate:date1];


You need to convert the input date to an NSDate object before you try and compare.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss +0000"];NSDate *startDate = [dateFormatter dateFromString:yourJSONDateString];NSDate *endDate = [NSDate date];CGFloat minuteDifference = [endDate timeIntervalSinceDate:startDate] / 60.0;

The formatter assumses the UTC offset will always be zero. If this isn't true, see Microsoft's date format string page for other format codes you can use.

--

Edit: the dateWithString method that everyone else used will be better to use in your situation, but the date formatter is necessary if the date format string you are getting isn't exactly right. I don't think I've ever used an API that sent dates in the correct format, perhaps I'm just unlucky :-(.


From below code you will get an idea for comparing two NSDate objects.

NSDate *dateOne = [NSDate dateWithString:@"2011-06-10 15:00:00 +0000"];NSDate *dateTwo = [NSDate dateWithString:@"2011-06-10 14:50:00 +0000"];switch ([dateOne compare:dateTwo]){    case NSOrderedAscending:         NSLog(@”NSOrderedAscending”);         break;    case NSOrderedSame:        NSLog(@”NSOrderedSame”);        break;    case NSOrderedDescending:       NSLog(@”NSOrderedDescending”);       break;}