比较两个NSDates的时间,忽略日期组件

时间:2012-01-25 09:22:52

标签: objective-c cocoa

我想将两个NSDates与NOW([NSDate date])进行比较。

NSDate *date1 = [NSDate dateWithString:@"1982-02-12 07:00:00 +0100"];
NSDate *now   = [NSDate dateWithString:@"2012-01-25 10:19:00 +0100"]; //example
NSDate *date2 = [NSDate dateWithString:@"1989-02-12 15:00:00 +0100"];

我想检查现在是否在date1和date2之间。在上面的例子中就是这种情况。应完全忽略日期组件,因此只应比较时间组件。我怎么能做到这一点?

提前致谢!

3 个答案:

答案 0 :(得分:26)

unsigned int flags = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSCalendar* calendar = [NSCalendar currentCalendar];

NSDateComponents* components = [calendar components:flags fromDate:date1];

NSDate* timeOnly = [calendar dateFromComponents:components];

这将为您提供一个日期对象,其中除了小时/分钟/秒之外的所有内容都已重置为某个常用值。然后你可以在它们上使用标准的NSDate比较函数。

供参考,以下是与您相反的问题:Comparing two NSDates and ignoring the time component

答案 1 :(得分:1)

您可以创建一个代表今天开始的日期,并将时间作为组件添加到其中以获取边界日期。

NSDate *now = [NSDate date];
NSDate *startOfToday;
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&startOfToday interval:NULL forDate:now];


NSDateComponents *startComps = [[NSDateComponents alloc] init];
startComps.hour = 7;
startComps.minute = 30;

NSDateComponents *endComps = [[NSDateComponents alloc] init];
endComps.hour = 20;

NSDate *startDate =  [[NSCalendar currentCalendar] dateByAddingComponents:startComps toDate:startOfToday options:0];
NSDate *endDate =  [[NSCalendar currentCalendar] dateByAddingComponents:endComps toDate:startOfToday options:0];

if ([startDate timeIntervalSince1970] < [now timeIntervalSince1970] && [now timeIntervalSince1970]  < [endDate timeIntervalSince1970]) {
    NSLog(@"good");
}

答案 2 :(得分:-2)

    NSDateFormatter* formatterDate = [[[NSDateFormatter alloc] init] autorelease]; 

    formatterDate.dateStyle = NSDateFormatterMediumStyle;  // whatever format you like  

    NSDate *first_Date  = [formatterDate dateFromString:@""];
    NSDate  *second_Date  = [formatterDate dateFromString:@""];
    NSDate  *todaysDate =  [NSDate date];


    NSTimeInterval timeIntFormFirstDate = [todaysDate timeIntervalSinceDate:First_Date];
    NSTimeInterval timeIntFronLastDate  = [second_Date timeIntervalSinceDate:todaysDate];

    int interval1 = timeIntFormFirstDate/60;
    int interval2 = timeIntFronLastDate/60;

    if (interval1 >0 && interval2 >0)
    {
        NSLog(@"Today's date is between first and second date");
    }