Subtracting two NSDate objects [duplicate]

2019-02-04 08:11发布

问题:

Possible Duplicate:
How to Get time difference in iPhone

I´m getting date and time from a JSON feed. I need to find the difference between the date I´m getting from the feed and today´s date and time. Any suggestions how I can do this?

I know I need to subtract the current date with the date I get from the feed, but I don´t know how to do it.

Ex:

Date from feed: Date: 2011-06-10 15:00:00 +0000 Today: Date: 2011-06-10 14:50:00 +0000

I need to display that the difference is ten minutes.

Thanks!

回答1:

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];


回答2:

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 :-(.



回答3:

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;
}