iphone - NSDate,比较两个日期

标签 iphone ios sdk nsdate

<分区>

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

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

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

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

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

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

最佳答案

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

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。

关于iphone - NSDate,比较两个日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9781467/

相关文章:

iphone - 如何在iPhone应用程序中暂停和恢复下载?

ios - Xcode - 将属性传递给 Storyboard 中的 View Controller

ios - 使用或不使用 iTunes 将 .ipa 安装到 iPad

php - Amazon AWS SDK PHP 2 - 按实例过滤标签?

ios - -[__ NSArrayI objectForKeyedSubscript:]:无法识别的选择器已发送到实例IN Xcode6 Objective-C iOS

iphone - 如何更改 UISearchBar 宽度

iphone - 如何解决这个问题签名无效,或者不是用Apple提交证书签名的。 (-19011)

ios - 将视频帧的长宽比转换为屏幕尺寸

c# - Facebook.Client 包安装错误

android - Facebook Android sdk 在身份验证时抛出丢失的重定向 uri