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日天(截至今天的日期)
只是看到 - > http://stackoverflow.com/questions/4463893/how-to-calculate-the-age-based-on-date – 2014-11-06 08:53:57
我已經嘗試過,但沒有得到確切的輸出 – vishnu 2014-11-06 08:54:58
試試這個 - > http ://stackoverflow.com/questions/19202120/how-to-compute-age-from-nsdate – 2014-11-06 08:59:03