⬇️时间戳转化为时间⬇️
//将时间戳转换为时间 (以毫秒为单位)
//参数:时间戳
//返回值格式:2019-04-19 10:33:35.886
- (NSString *)getTimestamp:(NSString*)mStr{
NSTimeInterval interval =[mStr doubleValue] / 1000.0;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Beijing"]];
NSString *dateString = [formatter stringFromDate: date];
NSLog(@"时间戳对应的时间是:%@",dateString);
return dateString;
}
//获取当前时间 (以毫秒为单位)
//返回值格式:2019-04-19 10:33:35.886
- (NSString *)getNowTimeTimestamp{
NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Beijing"]];
NSString *dateString = [formatter stringFromDate: datenow];
NSLog(@"当前时间戳对应的时间是:%@",dateString);
return dateString;
}
⬇️时间转化为时间戳⬇️
//将时间转化成 时间戳
//返回值格式:1555642454396
- (NSInteger)timeSwitchTimestamp:(NSString *)formatTime{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"]; //(@"YYYY-MM-dd hh:mm:ss") ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
[formatter setTimeZone:timeZone];
NSDate* date = [formatter dateFromString:formatTime]; //------------将字符串按formatter转成nsdate
//时间转时间戳的方法:
NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]*1000] integerValue];
NSLog(@"将某个时间转化成 时间戳timeSp:%ld",(long)timeSp); //时间戳的值
return timeSp;
}
//获取当前时间戳 (以毫秒为单位)
//返回值格式:1555642454396
//这里注意要获取完全部数值后在(long)强转, 如果(long)[datenow timeIntervalSince1970]*1000 这么写是先强转在*1000,就是秒级别的数据了
- (NSString *)nowTimeSwitchTimestamp{
NSDate *datenow = [NSDate date];//现在时间
//这里如果long不够用,就用(long long)
NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)];
return timeSp;
}
网友评论