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 g开发者_开发知识库et 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!
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;
}
精彩评论