[英]Can't compare two NSDates
Confused here... I have two dates which I NSLog to console and get: dates are 2011-03-30 13:33:57 +0000 - 2011-03-28 13:33:57 +0000
在这里感到困惑...我有两个日期可供NSLog控制台获取:日期为
2011-03-30 13:33:57 +0000 - 2011-03-28 13:33:57 +0000
One date is clearly later than the other... However, in the code below it doesn't matter if I use [dateUSERPREFS laterDate:dateXML]
or [dateUSERPREFS earlierDate:dateXML]
I get "we get first IF" displaying in the console? 一个日期显然比另一个日期晚。但是,在下面的代码中,无论我使用
[dateUSERPREFS laterDate:dateXML]
还是[dateUSERPREFS earlierDate:dateXML]
都不会在控制台中显示“我们得到第一个IF” ?
Any ideas? 有任何想法吗? Thanks,
谢谢,
NSDate *dateXML = [df dateFromString:last_modifiedXML];
NSDate *dateUSERPREFS = [df dateFromString:last_modifiedUSERPREFS];
NSLog(@"dates are %@ - %@", dateXML, dateUSERPREFS);
if ([dateUSERPREFS laterDate:dateXML]) {
NSLog(@"we get first IF");
}
[aDate laterDate:anotherDate]
returns an NSDate
, not a BOOL
. [aDate laterDate:anotherDate]
返回NSDate
而不是BOOL
。 Specifically, it returns the later of the two dates. 具体来说,它返回两个日期中的较晚日期。
You want to use compare:
instead: 您想使用
compare:
代替:
NSComparisonResult comparisonResult = [dateUSERPREFS compare:dateXML];
if (comparisonResult == NSOrderedAscending) {
// case where dateUSERPREFS is before dateXML
} else if (comparisonResult == NSOrderedSame) {
// both dates are the same
} else if (comparisonResult == NSOrderedDescending) {
// this could have just been a plain else; dateUSERPrefs after dateXML
}
Alternatively, you could use [dateUSERPREFS timeIntervalSinceDate:dateXML]
which gives you the (signed) number of seconds from dateXML
to dateUSERPREFS
. 另外,您可以使用
[dateUSERPREFS timeIntervalSinceDate:dateXML]
,它为您提供从dateXML
到dateUSERPREFS
的秒(带符号)秒数。
In the documentation, Apple says that laterDate returns the later of the two dates, not a BOOL statement. 苹果在文档中说,LaterDate返回两个日期中的较晚日期,而不是BOOL语句。
I'd do the following: subtract one date from the other and check if the value is more or less than zero. 我将执行以下操作:从另一个减去一个日期,然后检查该值是大于还是小于零。 That'd tell you which is larger:
那会告诉你哪个更大:
if ([dateXML timeIntervalSinceDate:dateUSERPREFS] > 0) {
//Now you know that dateXML is larger than dateUSERPREFS
}
-[NSDate laterDate:]
returns an NSDate *
not a BOOL
, and this won't be Null
, so the condition will always be true. -[NSDate laterDate:]
返回NSDate *
而不是BOOL
,并且它不会为Null
,因此条件将始终为true。
Try -[NSDate compare:]
which has the signature: 尝试使用
-[NSDate compare:]
,它具有以下签名:
- (NSComparisonResult)compare:(NSDate *)anotherDate
You can then compare the NSComparisonResult
in your if
condition, which is I believe what you are trying to achieve with the code in your question. 然后,您可以在
if
条件下比较NSComparisonResult
,这是我相信您要使用问题代码实现的目标。
(Of course, you could continue to use laterDate:
and just compare equality with the original object, but I feel compare:
makes for more intuitive logic) (当然,您可以继续使用
laterDate:
并仅将相等性与原始对象compare:
,但是我觉得compare:
使逻辑更直观)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.