// 比较两个时间的时间差
- (NSString *)pleaseInsertStarTime:(NSString *)time1 {
// 1.将时间转换为date
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
// 当前时间
NSDate *datenow = [NSDate date];
NSString *time2 = [formatter stringFromDate:datenow];
NSDate *date1 = [formatter dateFromString:time1];
NSDate *date2 = [formatter dateFromString:time2];
// 2.创建日历
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit type = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
// 3.利用日历对象比较两个时间的差值
NSDateComponents *cmps = [calendar components:type fromDate:date1 toDate:date2 options:0];
// 4.输出结果 NSLog(@"两个时间相差%ld年%ld月%ld日%ld小时%ld分%ld秒", cmps.year, cmps.month, cmps.day, cmps.hour, cmps.minute, cmps.second);
if (cmps.year != 0) {
return NSStringFormat(@"%ld年%ld月%ld日%ld小时%ld分%ld秒", cmps.year, cmps.month, cmps.day, cmps.hour, cmps.minute, cmps.second);
} else {
if (cmps.month != 0) {
return NSStringFormat(@"%ld月%ld日%ld小时%ld分%ld秒", cmps.month, cmps.day, cmps.hour, cmps.minute, cmps.second);
} else {
if (cmps.day != 0) {
return NSStringFormat(@"%ld日%ld小时%ld分%ld秒", cmps.day, cmps.hour, cmps.minute, cmps.second);
} else {
if (cmps.hour != 0) {
return NSStringFormat(@"%ld小时%ld分%ld秒", cmps.hour, cmps.minute, cmps.second);
} else {
if (cmps.minute != 0) {
return NSStringFormat(@"%ld分%ld秒", cmps.minute, cmps.second);
} else {
if (cmps.second != 0) {
return NSStringFormat(@"%ld秒", cmps.second);
} else {
return @"";
}
}
}
}
}
}
}