1、传入指定字符串,计算年龄,精确到年
/// 计算年龄
- (NSString *)calculateAge:(NSString *)birth {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
//生日
NSDate *birthDay = [dateFormatter dateFromString:birth];
//当前时间
NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
NSDate *currentDate = [dateFormatter dateFromString:currentDateStr];
NSTimeInterval time=[currentDate timeIntervalSinceDate:birthDay];
int age = ((int)time)/(3600*24*365);
return [NSString stringWithFormat:@"%d岁", age];
}
2、计算年龄差,精确到天
/// 计算年龄,精确到天
- (NSString *)calculateAgeDay:(NSString *)birth {
NSCalendar *calendar = [NSCalendar currentCalendar];//定义一个NSCalendar对象
NSDate *nowDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
//生日
NSDate *birthDay = [dateFormatter dateFromString:birth];
//用来得到详细的时差
unsigned int unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *date = [calendar components:unitFlags fromDate:birthDay toDate:nowDate options:0];
if([date year] >0)
{
return [NSString stringWithFormat:(@"%ld岁%ld月%ld天"),(long)[date year],(long)[date month],(long)[date day]];
NSLog(@"%@",[NSString stringWithFormat:(@"%ld岁%ld月%ld天"),(long)[date year],(long)[date month],(long)[date day]]) ;
}
else if([date month] >0)
{
return [NSString stringWithFormat:(@"%ld月%ld天"),(long)[date month],(long)[date day]];
NSLog(@"%@",[NSString stringWithFormat:(@"%ld月%ld天"),(long)[date month],(long)[date day]]);
}
else if([date day]>0){
return [NSString stringWithFormat:(@"%ld天"),(long)[date day]];
NSLog(@"%@",[NSString stringWithFormat:(@"%ld天"),(long)[date day]]);
}
else {
return @"0天";
NSLog(@"0天");
}
}