呆呆陈

博客园 首页 新随笔 联系 订阅 管理

 

- (NSString *)minutesAgo {

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

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

    NSDate *createdDate = [fmt dateFromString:self];

    

    // 判断发送时间 和 现在时间 的差距

    if (createdDate.isToday) { // 今天

        if (createdDate.deltaWithNow.hour >= 1) {

            fmt.dateFormat = @"HH:mm";

            return [fmt stringFromDate:createdDate];

        } else if (createdDate.deltaWithNow.minute >= 1) {

            return [NSString stringWithFormat:@"%ld分钟前", (long)createdDate.deltaWithNow.minute];

        } else {

            return @"刚刚";

        }

    } else if (createdDate.isYesterday) { // 昨天

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

        return [fmt stringFromDate:createdDate];

    } else if (createdDate.isThisYear) { // 今年(至少是前天)

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

        return [fmt stringFromDate:createdDate];

    } else {// 非今年

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

        return [fmt stringFromDate:createdDate];

    }

}

 

#pragma mark Comparing Dates

 

- (BOOL) isEqualToDateIgnoringTime: (NSDate *) aDate

{

NSDateComponents *components1 = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:self];

NSDateComponents *components2 = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:aDate];

return ((components1.year == components2.year) &&

(components1.month == components2.month) &&

(components1.day == components2.day));

}

 

- (BOOL) isToday

{

return [self isEqualToDateIgnoringTime:[NSDate date]];

}

 

- (BOOL) isYesterday

{

return [self isEqualToDateIgnoringTime:[NSDate dateYesterday]];

}

/**

 *  获得与当前时间的差距

 */

- (NSDateComponents *)deltaWithNow {

    NSCalendar *calendar = [NSCalendar currentCalendar];

    int unit = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;

    return [calendar components:unit fromDate:self toDate:[NSDate date] options:0];

}

 

/**

 *  是否为今年

 */

- (BOOL)isThisYear {

    NSCalendar *calendar = [NSCalendar currentCalendar];

    int unit = NSCalendarUnitYear;

    

    // 获得当前时间的年月日

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

    

    // 获得self的年月日

    NSDateComponents *selfCmps = [calendar components:unit fromDate:self];

    

    return nowCmps.year == selfCmps.year;

}

 

posted on 2017-01-05 14:05  我是一只萌妹子  阅读(176)  评论(0编辑  收藏  举报