【发布时间】:2011-08-20 17:37:25
【问题描述】:
我有一个设置为特定日期的事件。我想检查日期是否在当前日期的 5 分钟范围内。例如:如果事件设置为晚上 9:10,而现在是晚上 9:02。我想看看当前时间是否在晚上 9:05 到晚上 9:15 之间。
所以,我愿意...
NSDate *currentDate ... this variable contains the current date
NSDate *plusFive = [eventDate dateByAddingTimeInterval:300];
NSDate *minusFive = [eventDate dateByAddingTimeInterval:-300];
NSComparisonResult result1 = [eventDate compare:minusFive];
NSComparisonResult result2 = [eventDate compare:plusFive];
if ( (result1 == NSOrderedAscending) && (result2 == NSOrderedDescending) ) {
// if the current date is not inside the 5 minutes window
// or in other words, if the currentDate is lower than minusFive and bigger
// than plusFive
[self currentDateIsOutsideTheWindow];
} else {
[self currentDateIsInsideTheWindow];
}
问题是 result1 和 result2 总是给我 NSOrderedAscending 作为结果,任何日期。
有什么线索吗?
谢谢。
【问题讨论】:
-
你为什么用
eventDate而不是currentDate? -
我在我的答案中添加了一个快速代码示例......日期的
compare:方法似乎对我来说按预期工作,但我建议按照答案中的建议简化你的代码。
标签: iphone objective-c ios nsdate