How to calculate the age based on NSDate

后端 未结 11 1918
孤街浪徒
孤街浪徒 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:30

    Here's how you can calculate your actual age based on your birth date in years and days:

    NSString *birthDate = @"03/31/1990";    
    NSDate *todayDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    int time = [todayDate timeIntervalSinceDate:[dateFormatter dateFromString:birthDate]];
    int allDays = (((time/60)/60)/24);
    int days = allDays%365;
    int years = (allDays-days)/365;
    
    NSLog(@"You live since %i years and %i days",years,days);
    

    It returns the years and the exact days. And if you need you can change the NSDateFormatter and much more.

提交回复
热议问题