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];
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);
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];
}
return str;
}
转载请注明原文地址: https://ju.6miu.com/read-1000088.html