我有一个事件设置为特定的日期。我想检查日期是否在当前日期的5分钟范围内。例如:如果事件设置为晚上9:10,现在是晚上9:02。我想看看目前的时间是在9点05分到9点15分之间。iPhone - 比较日期不按预期工作
所以,我做...
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'? – jtbandes
我在我的答案中添加了一个快速代码示例...日期的'compare:'方法似乎按照我的预期工作,但我建议按照答案中的建议简化代码。 –
这是一个错字。谢谢。 – SpaceDog