• NSDate 刚刚、几分钟、几小时


    - (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;

    }

  • 相关阅读:
    第十二章 圆周率的计算问题分析
    第十一章:random库概述
    【模板】分治 FFT
    [PKUWC2018]Slay the Spire
    [PKUWC2018]随机算法
    [PKUWC2018]Minimax
    线段树合并初探
    平衡树初探
    Luogu P1613 跑路 题解报告
    CH138 兔子和兔子 题解报告
  • 原文地址:https://www.cnblogs.com/chenzq12/p/6252103.html
Copyright © 2020-2023  润新知