1.日期可以进行比较以确定大小或相等,也可以确定两个日期之间的时间间隔。两个日期的间隔时间差可以使用-timeIntervalSinceDate:方法来计算
- NSDate * now = [NSDate date];
- NSDate * anHourAgo = [now dateByAddingTimeInterval:-60*60];
- NSTimeInterVal timeBetween = [now timeIntervalSinceDate:anHourAgo];
- NSLog(@”%f”,timeBetween);
2.日期比较也可以使用-timeIntervalSinceNow方法获取和当前的时间间隔
- NSDate * anHourago = [NSDate dateWithTimeIntervalSinceNow;-60*60];
- NSTimeInterval interval = [anHourAgo timeIntervalSinceNow];
- NSLog(@”%f”,interval);
|
3.NSDate还提供了-laterDate、-earlierDate和compare方法来比较日期
- NSDate * now = [NSDate date];
- NSDate * anHourAgo = [now dateByAddingTimeInterval:-60*60];
- NSDate *result1 = [now laterDate:anHourAgo];
- NSDate * result2 = [now earlierDate:anHourAgo];
- NSComparisonResult result3 = [now compare:anHourAgo];
比较日期大小是任何编程语言都会经常遇到的问题,再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; }