简体   繁体   English

如何在iPhone中比较两个日期?

[英]How to compare two dates in iphone?

I want to compare the todays date and other date coming from my database. 我想比较今天的日期和我数据库中的其他日期。 For example, 2011-03-25 compare it with 2011-02-25 例如,2011-03-25与2011-02-25进行比较

How can i formate my database date as the NSDateFormatter require NSDdate datatype ? 由于NSDateFormatter需要NSDdate数据类型,我如何格式化数据库日期?

Cocoa has couple of methods for this: 可可对此有两种方法:

in NSDate 在NSDate

– isEqualToDate: – isEqualToDate:
– earlierDate: –较早的日期:
– laterDate: –以后的日期:
– compare: - 相比:

When you use - (NSComparisonResult)compare:(NSDate *)anotherDate ,you get back one of these: 当使用-(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.

for more read the SO post 有关更多信息,请阅读SO帖子

Just go through the blog post, there are many date related utility functions. 只要浏览一下博客文章,就有许多与日期相关的实用程序功能。

http://arstechnica.com/apple/guides/2010/03/how-to-real-world-dates-with-the-iphone-sdk.ars/2 http://arstechnica.com/apple/guides/2010/03/how-to-real-world-dates-with-the-iphone-sdk.ars/2

NSDate *date1 = [NSDate date];
NSDate *date2 = [NSDate date];

if ([date1 compare: date2]==NSOrderedAscending) {
    NSLog(@"YES");
}

In Swift : Swift中

let date1 = NSDate() //some date
let date2 = NSDate() //another date

let firstDate = date1.earlierDate(date2)
let lastDate = date1.laterDate(date2)

If your date are string like year-month-day, you can just compare string: 如果您的日期是类似于年-月-日的字符串,则可以比较字符串:

 if ([date1 compare:string2]==NSOrderedAscending) {
 } else if ([date1 compare:string2]== NSOrderedDescending) {
 } else {
 }

It will works because fields in date are from most important to less, like a string comparison. 之所以会这样,是因为date字段从最重要到最不重要,例如字符串比较。

您可以使用NSDate compare:或timeIntervalSinceReferenceDate-这将使您入门

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM