【问题标题】:NSDate, comparing two dates [duplicate]NSDate,比较两个日期[重复]
【发布时间】:2012-03-20 04:43:09
【问题描述】:

好的,我已经为此工作了几天,但被卡住了。我想做的是将当前时间与预定时间进行比较。我想要发生的是,每天在某些时间我希望某些代码触发,但不是在我指定的时间之前。

所以,基本上如果“当前时间”与“预定时间”相同或等于“预定时间”,则触发此代码。或者触发这行代码。

听起来很简单,但我无法比较这两次。

我已经将一个字符串格式化为这样的日期

     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];

那么我该如何比较这两次呢?我已经尝试了我能想到的一切,请帮助。

【问题讨论】:

    标签: iphone ios sdk nsdate


    【解决方案1】:

    你能试试下面的代码行吗?

    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 之间进行比较。

    【讨论】:

      【解决方案2】:

      试试这个条件:

      if ([date compare:currentTime]==NSOrderedSame) {
      
               //do want you want
      }
      

      【讨论】:

        【解决方案3】:

        假设您的问题实际上是比较两个 NSDate 对象,请尝试查看下面链接的问题;它有一些很好的指示;

        How to compare two dates in Objective-C

        【讨论】:

          猜你喜欢
          • 2011-08-03
          • 2012-05-30
          • 2011-08-09
          • 1970-01-01
          • 1970-01-01
          • 2014-07-16
          • 1970-01-01
          • 1970-01-01
          • 2015-07-08
          相关资源
          最近更新 更多