How to calculate the age based on NSDate

后端 未结 11 1928
孤街浪徒
孤街浪徒 2020-12-04 09:07

how to calculate the age based on the birth date in this format 6/24/1976 mon/date/year...

11条回答
  •  春和景丽
    2020-12-04 09:32

       -(NSInteger) ComputeYearMonth
        {
      NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd"];
    
    NSDate *DateOfBirth=[format dateFromString:[NSString stringWithFormat:@"%@-%@-%@",year,month,day]];
    NSDate *currentTime = [NSDate date];
    
    NSLog(@"DateOfBirth======%@",DateOfBirth);
    
    NSInteger years = [[[NSCalendar currentCalendar] components:NSYearCalendarUnit
                                                       fromDate:DateOfBirth
                                                         toDate:currentTime options:0]year];
    
    NSInteger months = [[[NSCalendar currentCalendar] components:NSMonthCalendarUnit
                                                        fromDate:DateOfBirth
                                                          toDate:currentTime options:0]month];
    NSLog(@"Number of years: %d",years);
    NSLog(@"Number of Months: %d,",months);
    
    
    
        return years;
      // End of Method
      }
    

提交回复
热议问题