json 减去两个 NSDate 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6306661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Subtracting two NSDate objects
提问by Magnus
Possible Duplicate:
How to Get time difference in iPhone
可能的重复:
如何在 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?
我正在从 JSON 提要中获取日期和时间。我需要找出我从提要中获得的日期与今天的日期和时间之间的差异。任何建议我怎么能做到这一点?
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 +0000Today: Date: 2011-06-10 14:50:00 +0000
来自提要的日期:Date: 2011-06-10 15:00:00 +0000今天:Date: 2011-06-10 14:50:00 +0000
I need to display that the difference is ten minutes.
我需要显示差异是十分钟。
Thanks!
谢谢!
回答by Sascha
Create two NSDate objects from the strings using NSDate's -dateWithString:, then get the difference of the two NSdate objects using
使用 NSDate's 从字符串创建两个 NSDate 对象-dateWithString:,然后使用获取两个 NSDate 对象的差异
NSTimeInterval diff = [date2 timeIntervalSinceDate:date1];
回答by kubi
You need to convert the input date to an NSDateobject before you try and compare.
NSDate在尝试比较之前,您需要将输入日期转换为对象。
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 pagefor other format codes you can use.
格式化程序假定 UTC 偏移量将始终为零。如果这不是真的,请参阅Microsoft 的日期格式字符串页面以了解您可以使用的其他格式代码。
--
——
Edit: the dateWithStringmethod 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 :-(.
编辑:dateWithString其他人使用的方法在您的情况下使用会更好,但如果您获得的日期格式字符串不完全正确,则日期格式化程序是必要的。我不认为我曾经使用过以正确格式发送日期的 API,也许我只是不走运:-(。
回答by Jhaliya
From below code you will get an idea for comparing two NSDateobjects.
从下面的代码中,您将了解比较两个NSDate对象。
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;
}

