版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1337704
(更新时间:2018-06-01 附上demo:https://gitee.com/liangsenliangsen/time_stamp_time_classification.git demo里有为NSObject写的一个分类,该分类具有将时间戳转化为时间的功能)
由于时间戳和时间的转换并不是很常用,所以在用到的时候也只是去网上找下代码。今天发现去网上找代码还是会耗费一定时间的,于是耗费时间找代码不如自己记录下代码以便下次使用。
上代码:
#pragma mark --- 将时间转换成时间戳
NSDateFormatter *formatter = [NSDateFormatteralloc init];
formatter setDateStyle:NSDateFormatterMediumStyle;
formatter setTimeStyle:NSDateFormatterShortStyle;
formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss";// ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
//设置时区,这个对于时间的处理有时很重要
//例如你在国内发布信息,用户在国外的另一个时区,你想让用户看到正确的发布时间就得注意时区设置,时间的换算.
//例如你发布的时间为2010-01-26 17:40:50,那么在英国爱尔兰那边用户看到的时间应该是多少呢?
//他们与我们有7个小时的时差,所以他们那还没到这个时间呢...那就是把未来的事做了
NSTimeZone* timeZone = NSTimeZonetimeZoneWithName:@"Asia/Shanghai";
formatter setTimeZone:timeZone;
NSDate *datenow = NSDatedate;//现在时间,你可以输出来看下是什么格式
NSString *nowtimeStr = formatterstringFromDate:datenow;//----------将nsdate按formatter格式转成nsstring
NSLog(@"%@", nowtimeStr);
// 时间转时间戳的方法:
NSString *timeSp = [NSStringstringWithFormat:@"%ld", (long)datenowtimeIntervalSince1970];
NSLog(@"timeSp:%@",timeSp);//时间戳的值
return timeSp;
}
#pragma mark ---- 将时间戳转换成时间
//将对象类型的时间转换为NSDate类型
double time =1504667976;
NSDate * myDate=NSDatedateWithTimeIntervalSince1970:time;
//设置时间格式
NSDateFormatter * formatter=[NSDateFormatterallocinit];
formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss";
//将时间转换为字符串
NSString *timeStr=formatterstringFromDate:myDate;
return timeStr;
}
同时希望能够帮到同样需要帮助的朋友们!
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有