美文网首页
27.字符串日期与秒数互转

27.字符串日期与秒数互转

作者: bytebytebyte | 来源:发表于2020-11-19 09:12 被阅读0次
- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *str = @"2016-09-13 21:47:06";
    NSTimeInterval seconds = [self dateStrToSeconds:str];
    NSLog(@"%f",seconds);
    NSLog(@"%@",[self secondsToDateStr:seconds]);
}

//字符串日期转秒数
-(NSTimeInterval)dateStrToSeconds:(NSString *)str
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *date = [formatter dateFromString:str];
    NSTimeInterval seconds = [date timeIntervalSince1970];
    return seconds;
}

//秒数转字符串日期
-(NSString *)secondsToDateStr:(NSTimeInterval)seconds
{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:seconds];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    return [formatter stringFromDate:date];

}

2016-09-14 21:35:44.348 时间转换[1436:129333] 1473774426.000000
2016-09-14 21:35:44.349 时间转换[1436:129333] 2016-09-13 21:47:06

总结:都得转为NSDate作为中介

相关文章

网友评论

      本文标题:27.字符串日期与秒数互转

      本文链接:https://www.haomeiwen.com/subject/azafmktx.html