//根据string 转化为 nsdate , 进而 根据nsdate 计算年龄
#import <Foundation/Foundation.h>
@interface NSDate (Extension)
+ (NSInteger)ageWithDateOfBirth:(NSDate *)date;
+ (NSDate *)dateFromString:(NSString *)string;
@end
#import "NSDate+Extension.h"
@implementation NSDate (Extension)
+ (NSInteger)ageWithDateOfBirth:(NSDate *)date;
{
// 出生日期转换 年月日
NSDateComponents *components1 = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:date];
NSInteger brithDateYear = [components1 year];
NSInteger brithDateDay = [components1 day];
NSInteger brithDateMonth = [components1 month];
// 获取系统当前 年月日
NSDateComponents *components2 = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
NSInteger currentDateYear = [components2 year];
NSInteger currentDateDay = [components2 day];
NSInteger currentDateMonth = [components2 month];
// 计算年龄
NSInteger iAge = currentDateYear - brithDateYear - 1;
if ((currentDateMonth > brithDateMonth) || (currentDateMonth == brithDateMonth && currentDateDay >= brithDateDay)) {
iAge++;
}
return iAge;
}
+ (NSDate *)dateFromString:(NSString *)string
{
//字符串转nsdate
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
//dateFormat 根据数据修改格式
[inputFormatter setDateFormat:@"yyyy/MM/dd"];
NSDate *date = [inputFormatter dateFromString:string];
return date;
}
@end