小記一筆,免得下次翻閱的時候,又浪費太多時間去驗證。
經常需要比對兩個時間的差距,當差距7天的時候就給出一定的提示等等什么的。
代碼如下:
1 - (BOOL)isOutOfDateTime { 2 3 //updateTime格式如下:2016-03-22 4 5 NSDateFormatter *format = [[NSDateFormatter alloc]init]; 6 //根據updateTime的格式,寫出對應的日期格式化串 7 [format setDateFormat:@"yyyy-MM-dd"]; 8 [format setLocale:[NSLocale currentLocale]]; 9 NSDate *currentDate = [format dateFromString:updateTime]; 10 11 //獲取當前的系統時間 12 NSDate *date = [NSDate date]; 13 //消除8小時的誤差。 14 NSTimeZone *zone = [NSTimeZone systemTimeZone]; 15 NSInteger interval = [zone secondsFromGMTForDate:date]; 16 17 //追加8小時 18 NSDate *localeDate = [date dateByAddingTimeInterval: interval]; 19 currentDate = [currentDate dateByAddingTimeInterval:interval]; 20 //計算時間差間隔 21 NSTimeInterval timeBetween = [localeDate timeIntervalSinceDate:currentDate]; 22 23 //根據相差的秒數,看是否大於7天 24 if (timeBetween > 7 * 24 * 3600) { 25 return YES; 26 } 27 return NO; 28 }
