iOS 时间和时间戳使用 2021-08-02

获取当前时间

- (NSString *)currentDateStr{
      NSDate *currentDate = [NSDate date];//获取当前时间,日期
      NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象
      [dateFormatter setDateFormat:@"YYYY/MM/dd hh:mm:ss SS "];//设定时间格式,这里可以设置成自己需要的格式
      NSString *dateString = [dateFormatter stringFromDate:currentDate];//将时间转化成字符串
      return dateString;
  }

获取当前时间戳

  - (NSString *)currentTimeStr{
        NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
        NSTimeInterval time=[date timeIntervalSince1970]*1000;// *1000 是精确到毫秒,不乘就是精确到秒
        NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
        return timeString;
  }

时间戳转时间,时间戳为13位是精确到毫秒的,10位精确到秒

     - (NSString *)getDateStringWithTimeStr:(NSString *)str{
        NSTimeInterval time=[str doubleValue]/1000;//传入的时间戳str如果是精确到毫秒的记得要/1000
NSDate *detailDate=[NSDate dateWithTimeIntervalSince1970:time];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; //实例化一个NSDateFormatter对象
//设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss SS"];
NSString *currentDateStr = [dateFormatter stringFromDate: detailDate];
return currentDateStr;
    }

字符串转时间戳

      - (NSString *)getTimeStrWithString:(NSString *)str{
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象
        [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; //设定时间的格式
        NSDate *tempDate = [dateFormatter dateFromString:str];//将字符串转换为时间对象
        NSString *timeStr = [NSString stringWithFormat:@"%ld", (long)                  [tempDate timeIntervalSince1970]*1000];//字符串转成时间戳,精确到毫秒*1000
        return timeStr;
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容