我是靠谱客的博主 沉默鞋垫,这篇文章主要介绍IOS 时间和时间戳之间转化示例,现在分享给大家,希望可以做个参考。

以毫秒为整数值的时间戳转换

时间戳转化为时间NSDate

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
- (NSString *)timeWithTimeIntervalString:(NSString *)timeString { // 格式化时间 NSDateFormatter* formatter = [[NSDateFormatter alloc] init]; formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"]; [formatter setDateStyle:NSDateFormatterMediumStyle]; [formatter setTimeStyle:NSDateFormatterShortStyle]; [formatter setDateFormat:@"yyyy年MM月dd日 HH:mm"]; // 毫秒值转化为秒 NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]/ 1000.0]; NSString* dateString = [formatter stringFromDate:date]; return dateString; }

时间转化为时间戳

复制代码
1
2
3
4
// 当前时间 NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0]; NSTimeInterval a=[date timeIntervalSince1970]*1000; // *1000 是精确到毫秒,不乘就是精确到秒 NSString *timeString = [NSString stringWithFormat:@"%.0f", a]; //转为字符型

通过比较时间与当前时间返回年月日的方法

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- (void)getBabyDetailAge:(NSString *)date { // 获得日期对象 NSDateFormatter *formatter_ = [[NSDateFormatter alloc] init]; formatter_.dateFormat = @"yyyy-MM-dd HH:mm:ss"; NSDate *createDate = [formatter_ dateFromString:date]; NSCalendar *gregorian = [[ NSCalendar alloc ] initWithCalendarIdentifier : NSCalendarIdentifierGregorian]; NSUInteger unitFlags = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear; NSDateComponents *components = [gregorian components:unitFlags fromDate:createDate toDate:[NSDate date] options: 0 ]; NSInteger years = [components year]; NSInteger months = [components month ]; NSInteger days = [components day ]; }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持靠谱客。

最后

以上就是沉默鞋垫最近收集整理的关于IOS 时间和时间戳之间转化示例的全部内容,更多相关IOS内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(106)

评论列表共有 0 条评论

立即
投稿
返回
顶部