ios 获取服务器时间转为 当前 几分钟之前 几小时 几天前

2019-01-25  本文已影响0人  java的小跟班

返回时间格式为格式为 2019-01-25 14:24:03

```

+ (NSString *)compareCurrentTime:(NSString *)str{

    //把字符串转为NSdate

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSDate *timeDate = [dateFormatter dateFromString:str];

    //得到与当前时间差

    NSTimeInterval timeInterval = fabs([[NSDate date] timeIntervalSinceDate:timeDate]);

    long temp = 0;

    NSString *result;

    if (timeInterval < 60) {

        result = [NSString stringWithFormat:@"刚刚"];

    }

    else if((temp = timeInterval/60) <60){

        result = [NSString stringWithFormat:@"%d分钟前",temp];

    }

    else if((temp = temp/60) <24){

        result = [NSString stringWithFormat:@"%d小时前",temp];

    }

    else if((temp = temp/24) <30){

        result = [NSString stringWithFormat:@"%d天前",temp];

    }

    else if((temp = temp/30) <12){

        result = [NSString stringWithFormat:@"%d月前",temp];

    }

    else{

        temp = temp/12;

        result = [NSString stringWithFormat:@"%d年前",temp];

    }

    return  result;

}

```

上一篇下一篇

猜你喜欢

热点阅读