IOS将时间转换为刚刚/N分钟前/今天几点几分/昨天几点几分表示法

使用IOS Objective-C语言,将当前时间戳,转换为刚刚/N分钟前/今天几点几分/昨天几点几分等易于理解的表示法,类似新浪微博的微博时间。
已邀请:
匿名用户

匿名用户

赞同来自:

- (NSString *)distanceTimeWithBeforeTime:(double)beTime
{
    NSTimeInterval now = [[NSDatedate]timeIntervalSince1970];
    double distanceTime = now - beTime;
    NSString * distanceStr;

    NSDate * beDate = [NSDatedateWithTimeIntervalSince1970:beTime];
    NSDateFormatter * df = [[NSDateFormatteralloc]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 && [nowDayintegerValue] == [lastDay integerValue]){//时间小于一天  
            distanceStr = [NSString stringWithFormat:@"今天 %@",timeStr];
    }  else if(distanceTime<24*60*60*2 && [nowDayintegerValue] != [lastDay integerValue]){
        if ([nowDay integerValue] - [lastDay integerValue] ==1 || ([lastDay integerValue] - [nowDayintegerValue] > 10 && [nowDayintegerValue] == 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;
}

要回复问题请先登录注册