根据生日计算周龄,下面贴上代码:
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
NSString *weeksAge = [self getWeeksAgeWithBirthday:@"2013-02-27"];
NSLog(@"weeksAge: %@", weeksAge);
}
//计算周龄
- (NSString *)getWeeksAgeWithBirthday:(NSString *)birthday
{
if (birthday && ![birthday isEqualToString:@""]) {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd"];
NSDate *curDate = [formatter dateFromString:birthday];
NSTimeInterval timeStamp = [curDate timeIntervalSince1970];
NSTimeInterval zhou = 60 * 60 * 24 * 7;
int f = ([[NSDate date] timeIntervalSince1970] - timeStamp ) / zhou;
if (f < 0) {
return [NSString stringWithFormat:@"还未出生"];
}
if (f % 52 == 0) {
return [NSString stringWithFormat:@"%d岁", f / 52];
}
return [NSString stringWithFormat:@"%d岁%d个月", f / 52, f % 52 / 4];
}
return @"生日信息错误";
}