美文网首页iOS 进阶
iOS 获取时间字符串与时间戳

iOS 获取时间字符串与时间戳

作者: 863cda997e42 | 来源:发表于2020-05-27 13:56 被阅读0次

    获取当前时间

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

    获取当前时间戳

    - (NSString *)getCurrentTimestamp {
        
        NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
        NSString *timeString = [NSString stringWithFormat:@"%0.f", time];
        return timeString;
    }
    

    时间戳转时间

    - (NSString *)getDateStringWithTimestamp:(NSString *)str {
        NSTimeInterval time = [str doubleValue];
        NSDate *detailDate = [NSDate dateWithTimeIntervalSince1970:time];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; // 实例化一个NSDateFormatter对象
        // 设定时间格式,这里可以设置成自己需要的格式
        [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
        NSString *currentDateStr = [dateFormatter stringFromDate:detailDate];
        return currentDateStr;
    }
    

    字符串转时间戳

    - (NSString *)getTimestampWithDate:(NSString *)str {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; // 创建一个时间格式化对象
        [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // 设定时间的格式
        NSDate *tempDate = [dateFormatter dateFromString:str]; // 将字符串转换为时间对象
        NSString *timeStr = [NSString stringWithFormat:@"%.0f", [tempDate timeIntervalSince1970]]; // 字符串转成时间戳,精确到秒
        return timeStr;
    }
    

    注意:iOS 返回的时间戳单位是秒。

    相关文章

      网友评论

        本文标题:iOS 获取时间字符串与时间戳

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