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;
}

 

转载于:https://www.cnblogs.com/wcLT/p/5109832.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值