温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-03-22 19:18:05 来源:网络 阅读:1037 作者:大头狼小鬼 栏目:移动开发
    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;
    
}


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI