iOS 计算日期时间差

NSDate *nowDate = [NSDate date];
NSDateFormatter *dateFomatter = [[NSDateFormatter alloc] init];
dateFomatter.dateFormat = @"yyyy-MM-dd";
 // 当前时间字符串格式
NSString *nowDateStr = [dateFomatter stringFromDate:nowDate];
NSDate *expireDate = [dateFomatter dateFromString:nowDateStr];
 // 要计算的时间    截止时间data格式
nowDate = [dateFomatter dateFromString:self.titleLabel.text];
 // 当前日历
NSCalendar *calendar = [NSCalendar currentCalendar];
// 需要对比的时间数据
NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
// 对比时间差
NSDateComponents *dateCom = [calendar components:unit fromDate:nowDate toDate:expireDate options:0];
NSLog(@"%@"dateCom.year) 
NSDateComponent可以得出的结果。
@property NSInteger era;
@property NSInteger year;
@property NSInteger month;
@property NSInteger day;
@property NSInteger hour;
@property NSInteger minute;
@property NSInteger second;
@property NSInteger nanosecond NS_AVAILABLE(10_7, 5_0);
@property NSInteger weekday;
@property NSInteger weekdayOrdinal;
@property NSInteger quarter NS_AVAILABLE(10_6, 4_0);
@property NSInteger weekOfMonth NS_AVAILABLE(10_7, 5_0);
@property NSInteger weekOfYear NS_AVAILABLE(10_7, 5_0);
@property NSInteger yearForWeekOfYear NS_AVAILABLE(10_7, 5_0);

你可能感兴趣的:(iOS 计算日期时间差)