怎么在IOS中将时间转换为时间戳

发布时间:2021-04-09 16:44:46 作者:Leah
来源:亿速云 阅读:311

怎么在IOS中将时间转换为时间戳?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

时间戳转化为时间NSDate

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

时间转化为时间戳

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

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

- (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中将时间转换为时间戳的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

推荐阅读:
  1. 如何在Vue.js中将时间转换成时间戳
  2. 怎么在C#中将时间与时间戳进行转换

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

ios 时间戳

上一篇:Win2003下如何简单配置APACHE+PHP5+MYSQL4+PHPMYADMIN

下一篇:win2003下如何安装配置 IIS6.0+PHP+MySQL

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》