方法一、NSDate自带的系统方法
日期之间比较可用以下方法 - (BOOL)isEqualToDate:(NSDate *)otherDate; 与otherDate比较,相同返回YES - (NSDate *)earlierDate:(NSDate *)anotherDate; 与anotherDate比较,返回较早的那个日期 - (NSDate *)laterDate:(NSDate *)anotherDate; 与anotherDate比较,返回较晚的那个日期 - (NSComparisonResult)compare:(NSDate *)other; 该方法用于排序时调用: . 当实例保存的日期值与anotherDate相同时返回NSOrderedSame . 当实例保存的日期值晚于anotherDate时返回NSOrderedDescending . 当实例保存的日期值早于anotherDate时返回NSOrderedAscending
方法二、对其中的 - (NSComparisonResult)compare:(NSDate *)other;进行封装
+(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];
if (result == NSOrderedDescending) {
//NSLog(@"oneDay比 anotherDay时间晚");
return 1;
}
else if (result == NSOrderedAscending){
//NSLog(@"oneDay比 anotherDay时间早");
return -1;
}
//NSLog(@"两者时间是同一个时间");
return 0;
}
方法二使用注意事项:首先,方法二的方法是一个类方法,我一般会把它写在NSDate的延展当中,或者把它写成一个对象方法,在对应的类中,使用self调用.其实,第二个方法是对年月日这三级进行比较,时分秒并没有添加进来如果需要的需要修改dateFormatter的@"dd-MM-yyyy"格式改成你想要比较的级数.