热门IT资讯网

IOS 距离现在的几分,几个小时,几分钟,几天,几周几月,几年

发表于:2024-11-24 作者:热门IT资讯网编辑
编辑最后更新 2024年11月24日,NSString *distanceTime = [self returnFromTheTimeOfToday:@"2016-09-29 01:45:10"];#pragma mark 默认一分钟有6
    NSString *distanceTime = [self returnFromTheTimeOfToday:@"2016-09-29 01:45:10"];#pragma mark 默认一分钟有60秒,一小时就60分钟 一天有24小时,一周有7天,一个月有30天,一年有12个月 不考虑其他的如平年2月28天,闰月29天这些情况- (NSString *)returnFromTheTimeOfToday:(NSString *)timeStr{    //timeStr 字符串格式->2016-09-29 01:45:10    NSDateFormatter *form = [[NSDateFormatter alloc] init];    //设置时区    form.locale = [NSLocale localeWithLocaleIdentifier:@"cn"];    form.dateFormat = @"yyyy-MM-dd HH:mm:ss";    NSDate *date = [form dateFromString:timeStr];        //得到当前的时间差    NSTimeInterval timeInterval = [date timeIntervalSinceNow];    timeInterval = -timeInterval;    //然后进行时间的比较    if(timeInterval < 60)    {        return [NSString stringWithFormat:@"刚刚"];    }    //分钟    NSInteger minute = timeInterval / 60;    if(minute < 60)    {        return [NSString stringWithFormat:@"%ld分钟之前",minute];    }    NSInteger hours = minute / 60;    if(hours < 24)    {        return [NSString stringWithFormat:@"%ld小时之前",hours];    }    NSInteger day = hours / 24;    NSInteger month = day/30;    NSInteger year = month/12;    if(day <= 1)    {        form.dateFormat = @"HH:mm";        NSString *oldtime = [form stringFromDate:date];        return [NSString stringWithFormat:@"昨天 %@",oldtime];    }    if(day < 7)    {        return [NSString stringWithFormat:@"%ld天之前",day];    }    if((day/7)<4)    {        return [NSString stringWithFormat:@"%ld周之前",day/7];    }    else if(month < 12)    {        return [NSString stringWithFormat:@"%ld月之前",month];    }    else    {        form.dateFormat = @"yyyy-MM-dd HH:mm";        return [NSString stringWithFormat:@"%ld年之前",year];    }    return nil;    }


0