一、获取系统时间并转化成字符串(打印出来是这个格式:yyyy-MM-dd HH:mm:ss)
NSDate * dateXT = [NSDate date];
NSCalendar * calendarXT = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *compXT = [calendarXT components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:dateXT];
NSString * stringXT = [NSString stringWithFormat:@"%ld-%ld-%ld %ld:%ld:%ld",(long)compXT.year, (long)compXT.month, (long)compXT.day, (long)compXT.hour, (long)compXT.minute, (long)compXT.second];
二、带年份的时间差(打印出来的是带年的时间差)
//创建时间对象
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSString *str = @"2014-05-13 21:34:55";
NSDate *date = [formatter dateFromString:str];
NSString *str1 = @"2016-02-8 22:49:33";
NSDate *date1 = [formatter dateFromString:str1];
//初始化日历
NSCalendar *calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
//拿到时间差
NSDateComponents *com = [calendar components:NSCalendarUnitYear |NSCalendarUnitMonth |NSCalendarUnitDay |NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:date toDate:date1 options:0];
NSLog(@"相差%ld年%ld个月%ld天%ld小时%ld分钟%ld秒", (long)com.year, (long)com.month, (long)com.day, (long)com.hour, (long)com.minute, (long)com.second);
三、不带年份的时间差(打印出来的是几天几分几秒)
//创建时间对象
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSString *str = @"2014-05-13 21:34:55";
NSDate *date = [formatter dateFromString:str];
NSString *str1 = @"2016-02-8 22:49:33";
NSDate *date1 = [formatter dateFromString:str1];
//初始化日历
NSCalendar *calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
//拿到时间差
NSDateComponents *com = [calendar components:NSCalendarUnitDay |NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:date0 toDate:date1 options:0];
//转化成秒(这样的时间可以转化成秒)
NSTimeInterval startToEndsec =(long)com.day *86400 + (long)com.hour *3600+(long)com.minute * 60+(long)com.second;
NSLog(@"相差%ld天%ld小时%ld分钟%ld秒", (long)com.day, (long)com.hour, (long)com.minute, (long)com.second);