簡體   English   中英

如何在iPhone中比較兩個日期?

[英]How to compare two dates in iphone?

我想比較今天的日期和我數據庫中的其他日期。 例如,2011-03-25與2011-02-25進行比較

由於NSDateFormatter需要NSDdate數據類型,我如何格式化數據庫日期?

可可對此有兩種方法:

在NSDate

– isEqualToDate:
–較早的日期:
–以后的日期:
- 相比:

當使用-(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.

有關更多信息,請閱讀SO帖子

只要瀏覽一下博客文章,就有許多與日期相關的實用程序功能。

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");
}

Swift中

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

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

如果您的日期是類似於年-月-日的字符串,則可以比較字符串:

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

之所以會這樣,是因為date字段從最重要到最不重要,例如字符串比較。

您可以使用NSDate compare:或timeIntervalSinceReferenceDate-這將使您入門

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM