android ios 时间戳,iOS 获取时间和时间戳以及使用

释放双眼,带上耳机,听听看~!

一、获取当前时间

// 获取当前时间

- (NSString *)getCurrentDate {

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 *)getCurrentTimestamp {

NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0]; // 获取当前时间0秒后的时间

NSTimeInterval time = [date timeIntervalSince1970]*1000;// *1000 是精确到毫秒(13位),不乘就是精确到秒(10位)

NSString *timeString = [NSString stringWithFormat:@"%.0f", time];

return timeString;

}

三、时间戳转时间

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

- (NSString *)getDateStringWithTimestamp:(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;

}

四、字符串转时间戳

// 字符串转时间戳 如:2017-4-10 17:15:10

- (NSString *)getTimestampWithDate:(NSString *)str {

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; // 创建一个时间格式化对象

[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SS"]; // 设定时间的格式

NSDate *tempDate = [dateFormatter dateFromString:str]; // 将字符串转换为时间对象

NSString *timeStr = [NSString stringWithFormat:@"%ld", (long)[tempDate timeIntervalSince1970]*1000]; // 字符串转成时间戳,精确到毫秒*1000

return timeStr;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值