IOS时间戳
什么是时间戳?
时间戳(timestamp),通常是一个字符序列,唯一地标识某一刻的时间。数字时间戳技术是数字签名技术一种变种的应用。
思考:简单来讲就是根据文件hash加密后生成的摘要和时间生成的时间凭证,它的数值是从1970年1月1日8点到现在时间的总的毫秒数
在Objective-C中如何将时间戳转换为NSDate?
NSString*str=@"1283376197";
NSTimeIntervaltime=[str doubleValue];
NSDate*detaildate=[NSDate dateWithTimeIntervalSince1970:time];
NSLog(@"date:%@",[detaildatedescription]);
思考:使用该函数,传递时间戳的double值就可以得到NSDate时间
如何将当前时间转换为时间戳?
NSDate *datenow =[NSDate date];//现在时间,你可以输出来看下是什么格式
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate:datenow];
NSDate *localeDate = [datenow dateByAddingTimeInterval: interval];
NSString *timeSp = [NSString stringWithFormat:@"%d", (long)[localeDate timeIntervalSince1970]];
NSLog(@"timeSp:%@",timeSp); //时间戳的值
思考:根据当前时间和系统所在时区得到和标准时间的Interval,然后得到效验后的时间localeDate,最后[localeDate timeIntervalSince1970]获取效验后的时间和1970年时间的差值,也就是时间戳
如何格式化输出NSDate?
NSDateFormatter*formatter = [[NSDateFormatter alloc]init];
[formattersetDateFormat:@"yyyy年MM月dd日"];
NSDate *date =[formatter stringFromDate:detaildate];
NSLog(@"date:%@",date);
思考:创建一个NSDateFormatter类,然后传递一个NSDate即可。“yyyyMMddHHMMss”分别代表年月日时分秒
-(NSString *)timeStamp:(NSString *)data{ //时间戳 NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ; [formatter setDateStyle:NSDateFormatterMediumStyle]; [formatter setTimeStyle:NSDateFormatterShortStyle]; [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制 NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"]; [formatter setTimeZone:timeZone]; // 时间戳转时间的方法 NSString *str = [NSString stringWithFormat:@"%@",data]; NSTimeInterval time=[str doubleValue]; NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:time]; //NSLog(@"1383523892 = %@",confromTimesp); NSString *confromTimespStr = [formatter stringFromDate:confromTimesp]; //NSLog(@"confromTimespStr = %@",confromTimespStr); NSString *timeString =[confromTimespStr substringWithRange:NSMakeRange(0,10)]; return timeString;}
浙公网安备 33010602011771号