栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > iOS

IOS 时间和时间戳之间转化示例

iOS 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/166882.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号