iOS计算两个日期的时间间隔,多少天数、周数、月数、年数、时、分、秒

iOS计算两个日期的时间间隔,多少天数、周数、月数、年数、时、分、秒

    //创建两个日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *startDate = [dateFormatter dateFromString:@"2017-07-26"];
    NSDate *endDate = [dateFormatter dateFromString:@"2021-09-01"];

    //利用NSCalendar比较日期的差异
    NSCalendar *calendar = [NSCalendar currentCalendar];
    /**
     * 要比较的时间单位,常用如下,可以同时传:
     *
     *    NSCalendarUnitDay : 天
     *    NSCalendarUnitYear : 年
     *    NSCalendarUnitMonth : 月
     *    NSCalendarUnitHour : 时
     *    NSCalendarUnitMinute : 分
     *    NSCalendarUnitSecond : 秒
     *    NSCalendarUnitWeekdayOrdinal : 星期
     */
    NSCalendarUnit unit = NSCalendarUnitWeekdayOrdinal;//只比较天数差异
    //比较的结果是NSDateComponents类对象
    NSDateComponents *delta = [calendar components:unit fromDate:startDate toDate:endDate options:0];
    //打印
    NSLog(@"%@",delta);
    //获取其中的"天"
    NSLog(@"day: %ld",delta.day);
    NSLog(@"era: %ld",delta.era);
    NSLog(@"year: %ld",delta.year);
    NSLog(@"month: %ld",delta.month);
    NSLog(@"hour: %ld",delta.hour);
    NSLog(@"minute: %ld",delta.minute);
    NSLog(@"second: %ld",delta.second);
    NSLog(@"weekday: %ld",delta.weekday);
    NSLog(@"weekdayOrdinal: %ld",delta.weekdayOrdinal);

你可能感兴趣的:(iOS计算两个日期的时间间隔,多少天数、周数、月数、年数、时、分、秒)