NSDate在两个给定的NSDates之间 [英] NSDate between two given NSDates
问题描述
我有兴趣创建一个方法来查找当前日期是否落在特定日期的特定时间之间。它是一个调度程序,所以我想找到当前时间发生什么事件。每天都有相同的一组时间:820-900,900-940,940-1020等等。因为这必须在任何给定的一天完成,我不知道如何创建一个NSDate有一定的时间。我认为这可能与NSTimeInterval完成,但我不知道如何实例化。
I am interested in creating a method to find if the current date falls between certain times on any given day. It is for a scheduling program, so I want to find what event is occurring at the current time. Every day has the same set of times: 820-900, 900-940, 940-1020, etc. Since this must be done on any given day I do not know how to create an NSDate with a certain time. I think this might be done with NSTimeInterval but I am not sure how to instantiate that.
推荐答案
这不是完美的,您可以使用[NSDate比较:]来检查您的日期与两个边界:
This isn't perfect, but you could use [NSDate compare:] to check your date against both boundaries:
NSDate *firstDate = ...
NSDate *secondDate = ...
NSDate *myDate = [NSDate date];
switch ([myDate compare:firstDate]) {
case NSOrderedAscending:
NSLog(@"myDate is older");
// do something
break;
case NSOrderedSame:
NSLog(@"myDate is the same as firstDate");
// do something
break;
case NSOrderedDescending:
NSLog(@"myDate is more recent");
// do something
break;
}
switch ([myDate compare:secondDate]) {
case NSOrderedAscending:
NSLog(@"myDate is older");
// do something
break;
case NSOrderedSame:
NSLog(@"myDate is the same as secondDate");
// do something
break;
case NSOrderedDescending:
NSLog(@"myDate is more recent");
// do something
break;
}
或更简单地:
BOOL between = NO;
if (([myDate compare:firstDate] == NSOrderedDescending) &&
([myDate compare:secondDate] == NSOrderedAscending)) {
between = YES;
}
我确定有一个更好的方法来做复杂的日期比较,应该工作。
I'm sure there's a better way to do complex date comparison, but this should work.
这篇关于NSDate在两个给定的NSDates之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!