iOS 判断某个时间距离当天间隔几天

方法一:

- (NSInteger)getDifferenceByDate:(NSDate *)oldDate {
        //获得当前时间
    NSDate *now = [NSDate date];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    unsigned int unitFlags = NSCalendarUnitDay;
    NSDateComponents *comps = [gregorian components:unitFlags fromDate:oldDate  toDate:now  options:0];
    return [comps day];
}

方法二:

- (NSInteger)getDifferenceByDate:(NSString *)date {
     //获得当前时间
    NSDate *now = [NSDate date];
    //实例化一个NSDateFormatter对象
   NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //设定时间格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *oldDate1 = [dateFormatter dateFromString: date];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    unsigned int unitFlags = NSCalendarUnitDay;
    NSDateComponents *comps = [gregorian components:unitFlags fromDate:oldDate  toDate:now  options:0];
    return [comps day];
}

你可能感兴趣的:(iOS 判断某个时间距离当天间隔几天)