objective-c - 如何在 Objective-C 中比较两个日期

标签 objective-c cocoa date date-comparison

我有两个日期:2009-05-11 和当前日期。我想检查给定日期是否为当前日期。这怎么可能。

最佳答案

Cocoa has couple of methods for this :

在 NSDate 中

– isEqualToDate:  
– earlierDate:  
– laterDate:  
– compare:

当你使用 - (NSComparisonResult)compare:(NSDate *)anotherDate 时,你会得到其中之一:

The receiver and anotherDate are exactly equal to each other, NSOrderedSame
The receiver is later in time than anotherDate, NSOrderedDescending
The receiver is earlier in time than anotherDate, NSOrderedAscending.

例子:

NSDate * now = [NSDate date];
NSDate * mile = [[NSDate alloc] initWithString:@"2001-03-24 10:45:32 +0600"];
NSComparisonResult result = [now compare:mile];

NSLog(@"%@", now);
NSLog(@"%@", mile);

switch (result)
{
    case NSOrderedAscending: NSLog(@"%@ is in future from %@", mile, now); break;
    case NSOrderedDescending: NSLog(@"%@ is in past from %@", mile, now); break;
    case NSOrderedSame: NSLog(@"%@ is the same as %@", mile, now); break;
    default: NSLog(@"erorr dates %@, %@", mile, now); break;
}

[mile release];

关于objective-c - 如何在 Objective-C 中比较两个日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/994855/

相关文章:

iOS:Google+ 按钮在 XIB 文件中不起作用?

iphone - 在解析 xml 文件之前处理 http 错误

Cocoa CoreData 和非基于文档的应用程序

java - JDBI:插入长整型日期(毫秒)

objective-c - 为什么不调用 UIPinchGestureRecognizer 而 scrollViewDidEndZooming 是?

ios - 来自 UITableViewCell 内 plist 的 UIProgressView 值

cocoa - 在 Storyboard中跨场景设置 NSTableView 的数据源

objective-c - 为什么 initWithCoder 不返回实例类型?

c# - WSDL 的 C# 中的日期时间到日期

Java:如何以 ISO 8601 SECOND 格式获取当前日期