pragma mark - 生日判斷
<pre>
-(NSString )dateToOld:(NSDate )bornDate{
//獲得當(dāng)前系統(tǒng)時(shí)間
NSDate currentDate = [NSDate date];
//獲得當(dāng)前系統(tǒng)時(shí)間與出生日期之間的時(shí)間間隔
NSTimeInterval time = [currentDate timeIntervalSinceDate:bornDate];
//時(shí)間間隔以秒作為單位,求年的話除以606024356
int age = ((int)time)/(360024365);
return [NSString stringWithFormat:@"%d",age];
}</pre>
<pre>
pragma mark - 精確到天數(shù)
-(NSString )dateToOld:(NSDate )bornDate{
//獲得當(dāng)前系統(tǒng)時(shí)間
NSDate currentDate = [NSDate date];
//獲得當(dāng)前系統(tǒng)時(shí)間與出生日期之間的時(shí)間間隔
NSTimeInterval time = [currentDate timeIntervalSinceDate:bornDate];
//時(shí)間間隔以秒作為單位,求年的話除以606024356
int age = ((int)time)/(360024365);
return [NSString stringWithFormat:@"%d",age];
}
pragma mark -根據(jù)出生日期返回詳細(xì)的年齡(精確到天)
-(NSString *)dateToDetailOld:(NSDate *)bornDate{
//獲得當(dāng)前系統(tǒng)時(shí)間
NSDate *currentDate = [NSDate date];
//創(chuàng)建日歷(格里高利歷)
NSCalendar *calendar = [NSCalendar currentCalendar];
//設(shè)置component的組成部分
NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond ;
//按照組成部分格式計(jì)算出生日期與現(xiàn)在時(shí)間的時(shí)間間隔
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天";
}
}
</pre>
原貼地址:http://www.reibang.com/p/fe6bd981b9f4