时间差的计算、系统时间

一、获取系统时间并转化成字符串(打印出来是这个格式: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);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容