- (void)viewDidLoad {
[superviewDidLoad];
NSDateFormatter *dateFormatter = [[NSDateFormatteralloc] init];
[dateFormattersetDateFormat:@"yyyy-MM-dd"];
NSDate* birth ;
NSNumber* age ;
//假设现在是2015年11月21日
//月小于今日
{
birth = [dateFormatterdateFromString:@"2014-10-20"];
//日小于今日 ;
age = [ViewControllercomputeAgeWithBirth:birth];
NSLog(@"age:%@ 应是:1",age);
birth = [dateFormatterdateFromString:@"2014-10-21"];
//日等于今日 ;
age = [ViewControllercomputeAgeWithBirth:birth];
NSLog(@"age:%@ 应是:1",age);
birth = [dateFormatterdateFromString:@"2014-10-22"];
//日大于今日 ;
age = [ViewControllercomputeAgeWithBirth:birth];
NSLog(@"age:%@ 应是:1",age);
}
//月等于今日
{
birth = [dateFormatterdateFromString:@"2014-11-20"];
// 日小于今日 ;
age = [ViewControllercomputeAgeWithBirth:birth];
NSLog(@"age:%@ 应是:1",age);
birth = [dateFormatterdateFromString:@"2014-11-21"];
//日等于今日;
age = [ViewControllercomputeAgeWithBirth:birth];
NSLog(@"age:%@ 应是:1",age);
birth = [dateFormatterdateFromString:@"2014-11-22"];
//日大于今日 ;
age = [ViewControllercomputeAgeWithBirth:birth];
NSLog(@"age:%@ 应是:0",age);
}
//月大于今日
{
birth = [dateFormatterdateFromString:@"2014-12-20"];
//日小于今日 ;
age = [ViewControllercomputeAgeWithBirth:birth];
NSLog(@"age:%@ 应是:0",age);
birth = [dateFormatterdateFromString:@"2014-12-21"];
//日等于今日;
age = [ViewControllercomputeAgeWithBirth:birth];
NSLog(@"age:%@ 应是:0",age);
birth = [dateFormatterdateFromString:@"2014-12-22"];
//日大于今日 ;
age = [ViewControllercomputeAgeWithBirth:birth];
NSLog(@"age:%@ 应是:0",age);
}
}
//由生日计算年龄
+(NSNumber*)computeAgeWithBirth:(NSDate*)birth{
/*
法律上计算年龄:如果1995年7月9日生,那么从2009年7月10日起你就已经14岁,到2010年7月10开始15岁。
*/
NSCalendar* calendar = [NSCalendarcurrentCalendar];
NSInteger birthYear = 0 ,birthMonth = 0, birthDay = 0;
NSInteger nowYear = 0 ,nowMonth = 0, nowDay = 0;
[calendargetEra:NULLyear:&birthYear month:&birthMonthday:&birthDay fromDate:birth];
[calendargetEra:NULLyear:&nowYear month:&nowMonthday:&nowDay fromDate:[NSDatedate]];
//只为测试
{
nowYear =2015;
nowMonth =11;
nowDay =21;
}
if(nowYear<birthYear){
return nil;
}
NSInteger age = nowYear - birthYear;
if(nowMonth<birthMonth
|| (nowMonth == birthMonth && nowDay<birthDay)){
age -=1;
}
return @(age);
}