NSDate,比较两个日期

11

好的,我已经在做这个问题上工作了几天,现在卡住了。我的目标是比较当前时间和预设时间。我想要的是,在特定时间每天触发某些代码,但不能在我指定的时间之前触发。

所以,基本上如果“当前时间”与“预设时间”相同或相等,则执行此代码。或者执行此行代码。

听起来很简单,但我在获取并比较两个时间方面遇到了麻烦。

我已将一个字符串格式化为日期,如下所示:

     NSString* dateString = @"11:05 PM";
        NSDateFormatter* firstDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        [firstDateFormatter setDateFormat:@"h:mm a"];
        [firstDateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
        NSDate* date = [firstDateFormatter dateFromString:dateString];
        NSLog(@"date %@",date);

然后我像这样获取当前时间

   NSDate *currentTime = [NSDate dateWithTimeIntervalSinceNow:[[NSTimeZone localTimeZone]     secondsFromGMT]];
NSDateComponents* comps = [[NSCalendar currentCalendar] 
                           components: NSHourCalendarUnit |NSMinuteCalendarUnit 
                                |NSSecondCalendarUnit fromDate:currentTime];
 [[NSCalendar currentCalendar] dateFromComponents:comps];

那么我应该如何比较这两个时间?我已经尝试了我所能想到的一切,请帮忙。

3个回答

21

你可以尝试以下代码:

switch ([dateOne compare:dateTwo]){
     case NSOrderedAscending:
          NSLog(@"NSOrderedAscending");
    break;
    case NSOrderedSame:
          NSLog(@"NSOrderedSame");
    break;
    case NSOrderedDescending:
         NSLog(@"NSOrderedDescending");
    break;
}

但在你的情况下,我认为你需要保持两个日期格式相同...或类似于这样的东西。

 NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
    [components setHour:23];//change your time to 24hrs formate 
    [components setMinute:05];
    [components setSecond:00];


    NSDate *dateOne = [[NSCalendar currentCalendar] dateFromComponents:components];

    components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];

     NSDate *dateTwo = [[NSCalendar currentCalendar] dateFromComponents:components];

并比较dateOne和dateTwo之间的差异。


3

尝试使用这个条件:

if ([date compare:currentTime]==NSOrderedSame) {

         //do want you want
}

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接