iOS-如何将生日转为年龄
2016-07-25 本文已影响1561人
Crazy赵宇小青年
序
因为公司没有专门的后台,所以很多数据处理只能压在前端判断处理。近期就遇见了将后台给的出生日期转换为年龄展现出来,因为对与时间有关的类不是很了解,所以查阅了一些资料,整理出来成为本篇文章,方便大家一起探讨。
废话不多说了,先把方法代码放出来。
1.根据出生日期返回年龄的方法
-(NSString *)dateToOld:(NSDate *)bornDate{
//获得当前系统时间
NSDate *currentDate = [NSDate date];
//获得当前系统时间与出生日期之间的时间间隔
NSTimeInterval time = [currentDate timeIntervalSinceDate:bornDate];
//时间间隔以秒作为单位,求年的话除以60*60*24*356
int age = ((int)time)/(3600*24*365);
return [NSString stringWithFormat:@"%d",age];
}
2.根据出生日期返回详细的年龄(精确到天)
-(NSString *)dateToDetailOld:(NSDate *)bornDate{
//获得当前系统时间
NSDate *currentDate = [NSDate date];
//创建日历(格里高利历)
NSCalendar *calendar = [NSCalendar currentCalendar];
//设置component的组成部分
NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond ;
//按照组成部分格式计算出生日期与现在时间的时间间隔
NSDateComponents *date = [calendar components:unitFlags fromDate:bornDate toDate:currentDate options:0];
//判断年龄大小,以确定返回格式
if( [date year] > 0)
{
return [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]];
}
else if([date day]>0)
{
return [NSString stringWithFormat:(@"%ld天"),(long)[date day]];
}
else {
return @"0天";
}
}
3.调用以上方法
NSString *birth = @"1995-10-30";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *birthDay = [dateFormatter dateFromString:birth];
NSLog(@"您的年龄:%@岁",[self dateToOld:birthDay]);
NSLog(@"您的年龄:%@",[self dateToDetailOld:birthDay]);
4.结果展示

关于时间的类
在iOS中关于时间的类:
- NSDate
- NSDateFormatter
- NSDateComponents
- NSCalendar
- NSTimeZone
......
大家如果想进一步了解关于时间类可以看看张永彬的《iOS时间那点事》一系列博客。《iOS时间那点事》
如果大家有更好的方法或是发现什么问题可以留言!