如何从NSDate计算年龄

编程入门 行业动态 更新时间:2024-10-27 06:20:59
本文介绍了如何从NSDate计算年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在制作一个应用程序,需要根据他们的生日找到某人的年龄。我有一个简单的 NSDate 但我如何用 NSDateFormatter 找到它?

I am working on an app that needs to find someones age depending on their birthday. I have a simple NSDate but how would I find this with NSDateFormatter?

推荐答案

- (NSInteger)ageFromBirthday:(NSDate *)birthdate { NSDate *today = [NSDate date]; NSDateComponents *ageComponents = [[NSCalendar currentCalendar] components:NSCalendarUnitYear fromDate:birthdate toDate:today options:0]; return ageComponents.year; }

NSDateFormatter 适用于格式化日期(呃!)。根据经验,只要您需要在 NSDate 上执行某些计算,就可以使用 NSCalendar 和相关联的类,例如 NSDateComponents 。

NSDateFormatter is for formatting dates (duh!). As a rule of thumb, whenever you need to perform some computation on an NSDate you use a NSCalendar and associated classes, such as NSDateComponents.

更多推荐

如何从NSDate计算年龄

本文发布于:2023-10-18 11:47:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504146.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:年龄   NSDate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!