美文网首页iOS Developer
iOS x分钟前/x小时前/x天前/x个月前/x年前代码片段

iOS x分钟前/x小时前/x天前/x个月前/x年前代码片段

作者: 孟豊Mike | 来源:发表于2016-12-04 14:02 被阅读64次

在显示一条数据更新时间的时候经常会用到,只需传入一份 date 就能返回具体时间

#pragma mark - 计算时间
- (NSString *)lastTimeOfChat:(NSDate *)date {
    
    NSString *str = @" ";
    NSDate *nowDate = [NSDate date];
    NSTimeInterval timeInterval = [nowDate timeIntervalSinceDate:date];
    //北京时间加8小时  除以86400得到的是天数
    if ((timeInterval + 60*60*8) / 86400 > 1 && (timeInterval + 60*60*8) / 86400 < 30) {
        
        NSString *min2 =  [NSString stringWithFormat:@"%d天前",(int)(timeInterval + 60*60*8) / 86400];
        str = min2;
    }
    //今天
    else if ((timeInterval + 60*60*8) / 86400 < 1) {
        
        if (timeInterval < 60) {
            str = @"刚刚";
        }
        else if(60 < timeInterval && timeInterval < 3600){
            NSString *min2 =  [NSString stringWithFormat:@"%d分钟前",(int)timeInterval/60];
            str = min2;
        }
        else{
            NSString *min2 =  [NSString stringWithFormat:@"%d小时前",(int)timeInterval/60/60];
            str = min2;
        }
    }
    //一个月前
    else if ((timeInterval + 60*60*8) / 86400 > 30) {
        NSString *min2 =  [NSString stringWithFormat:@"%d个月前",(int)(timeInterval + 60*60*8) / 2592000];
        str = min2;
    }
    return str;
}

相关文章

网友评论

    本文标题:iOS x分钟前/x小时前/x天前/x个月前/x年前代码片段

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