这个不难,只是记录下,方便自己和有需要的同学。
// 注意传入的 today 和 otherDay的时间格式为: yyyy-MM-dd hh:mm:ss 例子 2014-04-24 11:09:06
- (int)compareDate:(NSString*)today withDate:(NSString*)otherDay{
int ci;
NSDateFormatter *df = [[NSDateFormatter alloc] init];
today = [[today componentsSeparatedByString:@" "] objectAtIndex:0];
otherDay = [[otherDay componentsSeparatedByString:@" "] objectAtIndex:0];
[df setDateFormat:@"yyyy-MM-dd"];
NSDate *dt1 = [[NSDate alloc] init];
NSDate *dt2 = [[NSDate alloc] init];
dt1 = [df dateFromString:today];
dt2 = [df dateFromString:otherDay];
[NSDate timeIntervalSinceReferenceDate];
NSComparisonResult result = [dt1 compare:dt2];
switch (result)
{
//today比otherDay大
case NSOrderedDescending: {
NSTimeInterval dayTime = 24*60*60;
// 将today往前减少一天的时间,判断是否和昨天的时间是否相等,如果相等则表示
// otherDay为昨天
NSDate * newDate = [dt1 dateByAddingTimeInterval:-dayTime];
result = [dt2 compare:newDate];
if (result == NSOrderedSame) {
// 表示日期为昨天
ci = -1;
} else {
// 表示日期为昨天以前的时间
ci = 1;
}
}
break;
//date02=date01,代表日期是今天
case NSOrderedSame: ci=0;
break;
default:
// 默认显示所有的具体的日期时间
ci = 1;
break;
}
return ci;
}