序
因為公司沒有專門的后臺,所以很多數(shù)據(jù)處理只能壓在前端判斷處理。近期就遇見了將后臺給的出生日期轉(zhuǎn)換為年齡展現(xiàn)出來囊骤,因為對與時間有關(guān)的類不是很了解貌矿,所以查閱了一些資料示括,整理出來成為本篇文章秘通,方便大家一起探討为严。
廢話不多說了,先把方法代碼放出來肺稀。
1.根據(jù)出生日期返回年齡的方法
-(NSString *)dateToOld:(NSDate *)bornDate{
//獲得當前系統(tǒng)時間
NSDate *currentDate = [NSDate date];
//獲得當前系統(tǒng)時間與出生日期之間的時間間隔
NSTimeInterval time = [currentDate timeIntervalSinceDate:bornDate];
//時間間隔以秒作為單位,求年的話除以60*60*24*356
int age = ((int)time)/(3600*24*365);
return [NSString stringWithFormat:@"%d",age];
}
2.根據(jù)出生日期返回詳細的年齡(精確到天)
-(NSString *)dateToDetailOld:(NSDate *)bornDate{
//獲得當前系統(tǒng)時間
NSDate *currentDate = [NSDate date];
//創(chuàng)建日歷(格里高利歷)
NSCalendar *calendar = [NSCalendar currentCalendar];
//設(shè)置component的組成部分
NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond ;
//按照組成部分格式計算出生日期與現(xiàn)在時間的時間間隔
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.調(diào)用以上方法
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.結(jié)果展示
結(jié)果展示
關(guān)于時間的類
在iOS中關(guān)于時間的類:
- NSDate
- NSDateFormatter
- NSDateComponents
- NSCalendar
- NSTimeZone
......
大家如果想進一步了解關(guān)于時間類可以看看張永彬的《iOS時間那點事》一系列博客第股。《iOS時間那點事》
如果大家有更好的方法或是發(fā)現(xiàn)什么問題可以留言!