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

来源:互联网 发布:数据库设计说明书实例 编辑:程序博客网 时间:2024/06/10 23:57
两个时间之间的比较,相差多少天多少小时多少分多少秒
// 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];
    }
0 0
原创粉丝点击