比较两个时间相差的天数

比较两个时间相差的天数,如2020/06/30 13:30 和 2020/07/01 01:00 ,算相差一天,只要天数不同,就算相差一天

- (void)roundToDayWithDateComponents:(NSDateComponents *)components
{
    components.hour = 0;
    components.minute = 0;
    components.second = 0;
    components.nanosecond = 0;
}

- (NSInteger)getDeltaDaysFromDate:(NSDate *)fromDate toDate:(NSDate *)toDate
{
    NSDateComponents *from = [[NSCalendar currentCalendar] componentsInTimeZone:[NSTimeZone localTimeZone] fromDate:fromDate];
    [self roundToDayWithDateComponents:from];
    NSDateComponents *to = [[NSCalendar currentCalendar] componentsInTimeZone:[NSTimeZone localTimeZone] fromDate:toDate];
    [self roundToDayWithDateComponents:to];

    fromDate = [[NSCalendar currentCalendar] dateFromComponents:from];
    toDate = [[NSCalendar currentCalendar] dateFromComponents:to];
    NSInteger deltaDate = ([toDate timeIntervalSince1970] - [fromDate timeIntervalSince1970]) / 3600 / 24;
    return (NSInteger)abs((int)deltaDate);
}

你可能感兴趣的:(比较两个时间相差的天数)