如何根据NSDate计算年龄
如何根据出生日期计算年龄,格式为 6/24/1976 mon/date/year...
how to calculate the age based on the birth date in this format 6/24/1976 mon/date/year...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
其中许多答案都没有正确考虑闰年,因此,最好是使用 Apple 的方法而不是除以常量。
Swift
Objective-C
我认为这比这里的任何其他答案都更干净、更准确。
编辑
通过将
生日
和现在
设置为中午来提高准确性。这是使用Date
扩展(在 Swift 中)实现此目的的一种方法...Many of these answers don't properly account for leap years and such, best is to use Apple's methods instead of dividing by constants.
Swift
Objective-C
I think this is cleaner and more accurate than any of the other answers here.
Edit
Increase accuracy by setting both
birthday
andnow
to noon. Here is one way to do that with aDate
extension (in Swift)...以下是如何根据您的出生日期(以年和日为单位)计算您的实际年龄:
它返回年份和确切的天数。如果您需要,您可以更改 NSDateFormatter 等等。
Here's how you can calculate your actual age based on your birth date in years and days:
It returns the years and the exact days. And if you need you can change the NSDateFormatter and much more.
这是我从中得到的代码 链接..效果很好..输出将类似于“5年6个月”,并且所有用例都包含在其中。
如果您希望年龄为 int ,请尝试以下答案..这是我从以下 链接
希望这对某人有帮助..
This is the code I got from this link.. it works great.. Out put will be like "5 years 6 months" and all usecases are covered in it.
If you want age as int try the following answer.. which I got from following link
Hope this helps some one..
如果你想单独找到年龄。请使用下面的一个,其中也包括闰年计算
If u want to find age alone .use below one which include leap year calculation too
一个简单易用的快速扩展来获取年龄/多少岁是
NSDate
示例:
顺便说一句,你应该小心,这是西方的年龄概念,其他一些国家的计算方式有所不同(例如韩国)。
A simple to use swift extension to get the age/how old is a
NSDate
Exemple:
By the way, you should be careful, this is the western conception of age, the counting is different in some other countries (Korea for exemple).
也许我错了,但这更简单,不是吗?
May be I'm wrong, but this is simpler, isn't it?
基于 cobbal 的解决方案的 Swift 3+ 语法方法。
Method in Swift 3+ syntax based on cobbal's solution.
最简单的方法是使用 NSCalendar:
the easiest way is to use the NSCalendar:
这是一个计算年龄的函数(Swift 2.1)
Here's a function to calculate age (Swift 2.1)