2014-11-06 80 views
0

我想以X年Y月Z日的形式計算年齡。這裏是我的代碼如何計算ios中的年齡?

NSString *dateString = @"15-Sep-1997"; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 
[dateFormatter setDateFormat:@"dd-MMM-yyyy"]; 

NSDate *PrevDate = [dateFormatter dateFromString:dateString]; 


NSDate *today = [NSDate date]; 
NSLog(@"Prev date = %@", PrevDate); 
NSLog(@"today =%@", today); 
NSInteger years; 
NSInteger months; 
NSInteger days; 

NSCalendar *calendar = [NSCalendar currentCalendar]; 
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit; 
NSDateComponents *dateComponentsNow = [calendar components:unitFlags fromDate:today]; 
NSDateComponents *dateComponentsBirth = [calendar components:unitFlags fromDate:PrevDate]; 

if (([dateComponentsNow month] < [dateComponentsBirth month]) || 
    (([dateComponentsNow month] == [dateComponentsBirth month]) && ([dateComponentsNow day] < [dateComponentsBirth day]))) { 
    years = [dateComponentsNow year] - [dateComponentsBirth year] - 1; 
} else { 
    years = [dateComponentsNow year] - [dateComponentsBirth year]; 
    months = [dateComponentsNow month] - [dateComponentsBirth month]; 
    days = [dateComponentsNow day] - [dateComponentsBirth day]; 
} 


NSLog(@"%d years %d months %d days", years, months, days); 

輸出變爲:17歲2個月 - 9日(它抽出1個多月,並減去天) 正確的輸出:17年2本月22日天(截至今天的日期)

+1

只是看到 - > http://stackoverflow.com/questions/4463893/how-to-calculate-the-age-based-on-date – 2014-11-06 08:53:57

+0

我已經嘗試過,但沒有得到確切的輸出 – vishnu 2014-11-06 08:54:58

+0

試試這個 - > http ://stackoverflow.com/questions/19202120/how-to-compute-age-from-nsdate – 2014-11-06 08:59:03

回答

8

查看下方代碼。

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"dd-MMM-yyyy"]; 
NSDate *startD = [dateFormatter dateFromString:@"15-Sep-1997"]; 
NSDate *endD = [NSDate date]; 

NSCalendar *calendar = [NSCalendar currentCalendar]; 
NSUInteger unitFlags = NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond; 
NSDateComponents *components = [calendar components:unitFlags fromDate:startD toDate:endD options:0]; 

NSInteger year = [components year]; 
NSInteger month = [components month]; 
NSInteger day = [components day]; 

NSLog(@"%ld:%ld:%ld", (long)year, (long)month,(long)day); 

和輸出

17:1:22

也許這會幫助你。

+0

工作很好,非常感謝你。 – vishnu 2014-11-06 09:26:08