Subtracting two NSDate objects [duplicate]

假如想象 提交于 2019-11-30 06:00:57

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!