轉自:http://www.myext.cn/other/a_30922.html
比較日期大小是任何編程語言都會經常遇到的問題,再iOS編程中,通常用NSDate對象來存儲一個時間(包括日期和時間、時區),而且 NSDate類提供了compare方法來進行時間的比較,但有時不想那么精確的知道兩個日期的大小(默認會比較到秒),可以用下面的實現方法:
+(int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
NSComparisonResult result = [dateA compare:dateB];
NSLog(@"date1 : %@, date2 : %@", oneDay, anotherDay);
if (result == NSOrderedDescending) {
//NSLog(@"Date1 is in the future");
return 1;
}
else if (result == NSOrderedAscending){
//NSLog(@"Date1 is in the past");
return -1;
}
//NSLog(@"Both dates are the same");
return 0;
}