将json形式的时间字符串转换成正常的形式

 

 

 

//重写timegetter方法

//判断addtime和当期的时间差

// < 60分钟  返回 n分钟前

// > 60分钟  返回 n小时前

//超过24小时  返回 --

 

- (NSString *)time{

    // 1 先把json中的数字转换成日期对象

    //把拿到的json中的时间的字符串转换成我们熟悉的时间格式

    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[self.addtime intValue]];

    // 2 计算date和当前的时间差

    NSCalendar *calendar = [NSCalendar currentCalendar];

    

    //获取两个时间相差的分钟

    NSDateComponents *component = [calendar components:NSCalendarUnitMinute fromDate:date toDate:[NSDate date] options:0 ];

    //相差的分钟

    if(component.minute < 60){

        return [NSString stringWithFormat:@"%zd分钟前",component.minute];

        

    }

    

    component = [calendar components:NSCalendarUnitHour fromDate:date toDate:[NSDate date] options:0 ];

 

    //相差的小时

    if(component.hour < 24){

        return [NSString stringWithFormat:@"%zd小时前",component.hour];

    }

    

    //date 转成月日

    //格式化日期的对象

        NSDateFormatter *ndf = [NSDateFormatter new];

        ndf.dateFormat = @"MM-dd";

        return [ndf stringFromDate:date];

        

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

原文地址:https://www.cnblogs.com/LiLihongqiang/p/5617181.html