我想以X年Y个月Z天的形式计算年龄。这是我的代码
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年1个月22天(截至今日)
答案 0 :(得分: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
也许这会对你有帮助。