//获取当前时间
+ (NSString *)currentDateStr{NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
//设置时区,这个对于时间的处理有时很重要
NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
[formatter setTimeZone:timeZone];
NSDate *datenow = [NSDate date];//现在时间
NSString *dateString = [formatter stringFromDate:datenow];
return dateString;
}
//获取当前时间戳
+ (NSString *)currentTimeStr{//获取当前时间0秒后的时间
NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];
// *1000 是精确到毫秒,不乘就是精确到秒
NSTimeInterval time=[date timeIntervalSince1970]*1000;
NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
return timeString;
}
// 时间戳转时间,时间戳为13位是精确到毫秒的,10位精确到秒
+ (NSString *)getDateStringWithTimeStr:(NSString *)str{//传入的时间戳str如果是精确到毫秒的记得要/1000
NSTimeInterval time=[str doubleValue]/1000;
NSDate *detailDate=[NSDate dateWithTimeIntervalSince1970:time];
//实例化一个NSDateFormatter对象
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//设定时间格式,这里可以设置成自己需要的格式
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss SS"];
NSString *currentDateStr = [dateFormatter stringFromDate: detailDate];
return currentDateStr;
}
//字符串转时间戳
+ (NSInteger)getTimeStrWithString:(NSString *)str{NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
//设置时区,这个对于时间的处理有时很重要
NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
[formatter setTimeZone:timeZone];
//将字符串按formatter转成nsdate
NSDate* date = [formatter dateFromString:str];
//时间转时间戳的方法:
NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]*1000] integerValue];
return timeSp;
}
//获取两个时间的间隔
+ (long long)getDurationDateStartTime:(NSString *)startTime endTime:(NSString *)endTime {
if (startTime && endTime) {
NSDateFormatter *strDateStr = [[NSDateFormatter alloc]init];
[strDateStr setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
NSDate *startdate = [strDateStr dateFromString:startTime];
NSDate *enddate = [strDateStr dateFromString:endTime];
//时间转时间戳的方法:
NSTimeInterval aTime = [enddate timeIntervalSinceDate:startdate];
return (long long)aTime;
} else {
return -1;
}
}
//持续时间(时间戳取差值)
+ (long long)getDurationTimeStartTime:(NSString *)startTime endTime:(NSString *)endTime {
if (startTime && endTime) {
long long aTime = [endTime longLongValue] - [startTime longLongValue];
return aTime;
} else {
return -1;
}
}