美文网首页
时间戳转换为近距离时间状态

时间戳转换为近距离时间状态

作者: 金约21依代 | 来源:发表于2017-09-15 18:14 被阅读0次

    简单时间戳转换

    - (NSString *)timeFromTimeStep:(NSString *)timesStamp
    {
        // 格式化时间
        NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
        formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
        [formatter setDateStyle:NSDateFormatterMediumStyle];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        [formatter setDateFormat:@"MM-dd HH:mm"];
        
        // 毫秒值转化为秒/1000,本身为秒则不除1000
        NSDate * date = [NSDate dateWithTimeIntervalSince1970:[timesStamp doubleValue]];
        NSString *dateString = [formatter stringFromDate:date];
        return dateString;
    }
    

    时间戳转换为近距离时间状态

    + (NSString *)timeTextWithTimesStamp:(double)timesStamp
    {
        NSTimeInterval now = [[NSDate date]timeIntervalSince1970];
        double distanceTime = now - timesStamp;
        NSString * distanceStr;
        
        NSDate * beDate = [NSDate dateWithTimeIntervalSince1970:timesStamp];
        NSDateFormatter * df = [[NSDateFormatter alloc]init];
        [df setDateFormat:@"HH:mm"];
        NSString * timeStr = [df stringFromDate:beDate];
        
        [df setDateFormat:@"dd"];
        NSString * nowDay = [df stringFromDate:[NSDate date]];
        NSString * lastDay = [df stringFromDate:beDate];
        
        if (distanceTime < 60)
        {//小于一分钟
            distanceStr = @"刚刚";
        }
        else if (distanceTime <60*60)
        {//时间小于一个小时
            distanceStr = [NSString stringWithFormat:@"%ld分钟前",(long)distanceTime/60];
        }
        else if(distanceTime <24*60*60 && [nowDay integerValue] == [lastDay integerValue])
        {//时间小于一天
            distanceStr = [NSString stringWithFormat:@"%ld小时前",(long)distanceTime/60/60];
        }
        else if(distanceTime<24*60*60*2 && [nowDay integerValue] != [lastDay integerValue])
        {
            
            if ([nowDay integerValue] - [lastDay integerValue] ==1 || ([lastDay integerValue] - [nowDay integerValue] > 10 && [nowDay integerValue] == 1))
            {
                distanceStr = [NSString stringWithFormat:@"昨天 %@",timeStr];
            }
            else
            {
                [df setDateFormat:@"MM-dd HH:mm"];
                distanceStr = [df stringFromDate:beDate];
            }
            
        }
        else if(distanceTime <24*60*60*365)
        {
            [df setDateFormat:@"MM-dd HH:mm"];
            distanceStr = [df stringFromDate:beDate];
        }
        else
        {
            [df setDateFormat:@"yyyy-MM-dd HH:mm"];
            distanceStr = [df stringFromDate:beDate];
        }
        return distanceStr;
    }
    

    相关文章

      网友评论

          本文标题:时间戳转换为近距离时间状态

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