iPhone-比较日期无法正常工作 [英] iPhone - comparing dates not working as expected

查看:45
本文介绍了iPhone-比较日期无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个设置为特定日期的事件.我想检查日期是否在当前日期的5分钟范围内.例如:如果事件设置为9:10 pm,现在是9:02 pm.我想看看当前时间是否在9:05到9:15 pm之间.

I have an event that is set to a particular date. I want to check if the date is within 5 minutes range of the current date. For example: if the event is set to 9:10 pm, and now is 9:02 pm. I want to see if the current time is between 9:05 and 9:15 pm.

所以,我愿意...

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作为结果,在任何日期.

the problem is that result1 and result2 always gives me NSOrderedAscending as a result, for any date.

有任何线索吗?

谢谢.

推荐答案

尝试以下代码.

NSTimeInterval ti = [eventDate timeIntervalSinceDate:currentDate];
if (ti > 0 && ti < 300) ...
else if (ti < 0 && ti > -300) ...

这篇关于iPhone-比较日期无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆