您的位置:首页 > 移动开发 > IOS开发

ios 两个时间之间的比较,相差多少天多少小时多少分多少秒

2016-12-04 22:06 525 查看
两个时间之间的比较,相差多少天多少小时多少分多少秒

// 1. 今年

    // 1分钟内:刚刚

    // 1分~59分内:xx小时前

    // 昨天 xx:xx

    // xx-xx xx:xx

    

    // 2. 非今年

    // xxxx-xx-xx xx:xx

    

    // Wed Jul 08 10:01:03 +0800 2015

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

    // 如果是真机调试,转换这种欧美时间,需要设置locale

    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

    fmt.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy";

    NSDate *createDate = [fmt dateFromString:_created_at];

    

    // 当前时间

    NSDate *now = [NSDate date];

    // 日历对象 (方便比较两个日期之间的差距)

    NSCalendar *calendar = [NSCalendar currentCalendar];

    // NSCalendarUnit 枚举代表想获得哪些差值

    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitWeekOfMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;

    // 计算两个日期之间的差值

    NSDateComponents *cmps = [calendar components:unit fromDate:createDate toDate:now options:0];

    

    // 获得某个时间的年月日时分秒

    NSDateComponents *createDateCmps = [calendar components:unit fromDate:createDate];

    NSDateComponents *nowCmps = [calendar components:unit fromDate:now];

    

    if (createDateCmps.year == nowCmps.year) { // 今年

        if (cmps.day == 1) { // 昨天

            fmt.dateFormat = @"昨天 HH:mm";

            return [fmt stringFromDate:createDate];

        } else if (cmps.day == 0){ // 今天

            if (cmps.hour > 1) { // 大于1小时前

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

            }

            else if (cmps.minute >= 1) {

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

            }

            else {

                return @"刚刚";

            }

        }

        else { // 今年的其他日子

            fmt.dateFormat = @"MM-dd HH:mm";

            return [fmt stringFromDate:createDate];

        }

    }

    else { // 非今年

        fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";

        return [fmt stringFromDate:createDate];

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: