两个给定 NSDate 之间的 NSDate [英] NSDate between two given NSDates

查看:41
本文介绍了两个给定 NSDate 之间的 NSDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有兴趣创建一种方法来查找当前日期是否介于任何给定日期的特定时间之间.它用于调度程序,因此我想查找当前时间正在发生的事件.每天都有相同的时间集: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 compare:] 来检查您的日期与两个边界的对比:

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 之间的 NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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