iOS 计算两个日期字符串的差值

    xiaoxiao2021-12-15  49

    iOS 计算两个日期字符串的差值

    写在前面

    最近的项目中,由于写服务器的大兄弟总是爱将日期以字符串的形式传给前端,而前端要显示两个日期的差值,所以自己写了一个工具方法来进行转换,写下来方便自己以后翻阅,同时也分享给大家。

    代码如下

    - (NSString *)getTotalTimeWithStartTime:(NSString *)startTime endTime:(NSString *)endTime{ //按照日期格式创建日期格式句柄 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; NSTimeZone *localTimeZone = [NSTimeZone localTimeZone]; [dateFormatter setTimeZone:localTimeZone]; //将日期字符串转换成Date类型 NSDate *startDate = [dateFormatter dateFromString:startTime]; NSDate *endDate = [dateFormatter dateFromString:endTime]; //将日期转换成时间戳 NSTimeInterval start = [startDate timeIntervalSince1970]*1; NSTimeInterval end = [endDate timeIntervalSince1970]*1; NSTimeInterval value = end - start; //计算具体的天,时,分,秒 int second = (int)value %60;//秒 int minute = (int)value / 60 % 60; int house = (int)value / 3600; int day = (int)value / (24 * 3600); //将获取的int数据重新转换成字符串 NSString *str; if (day != 0) { str = [NSString stringWithFormat:@"%d天%d小时%d分%d秒",day,house,minute,second]; }else if (day==0 && house != 0) { str = [NSString stringWithFormat:@"%d小时%d分%d秒",house,minute,second]; }else if (day== 0 && house== 0 && minute!=0) { str = [NSString stringWithFormat:@"%d分%d秒",minute,second]; }else{ str = [NSString stringWithFormat:@"%d秒",second]; } //返回string类型的总时长 return str; }
    转载请注明原文地址: https://ju.6miu.com/read-1000088.html

    最新回复(0)