PHP 准确计算给定出生日期的最近年龄
我正在尝试根据出生日期计算最接近的年龄,但我不知道该怎么做。我尝试过一些估计方法,但这还不够好。我们需要计算从今天到下一个生日的天数,无论是今年还是明年。并再次计算从今天到上一个生日的天数,无论是今年还是去年。
有什么建议吗?
I am trying to calculate the nearest Age based on DOB, but i cant wrap my head around how to do it. I have tried some methods which estimates but this is not good enough. We need to calculate the days from today and the next birthday, whether it is in the current year or next year. and also calculate the days from today and the last birthday again whether it is in the current year or last year.
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为这就是你想要的......当然,你可以让一个人的年龄精确到当天,并将其向上或向下舍入到最接近的年份......这可能是我应该做的。
这是相当暴力的,所以我相信你可以做得更好,但它所做的是检查距离今年、明年和去年生日的天数(我分别检查了这三个生日,而不是从 365 中减去) ,因为 date() 负责闰年,但我不想这样做)。然后,它从这些生日中最接近的一个开始计算年龄。
工作示例
编辑:删除不必要的
date()$time_until
计算中的 code>。I think this is what you want.... of course, you could just get a persons age accurate to the day and round it up or down to the closest year..... which is probably what I should have done.
It's quite brute force, so I'm sure you can do it better, but what it does is check the number of days until this year's, next year's, and last year's birthday (I checked each of those three separately instead of subtracting from 365, since date() takes care of leap years, and I don't want to). Then it calculates age from whichever one of those birthdays is closest.
Working example
Edit: Removed unnecessary
date()
s in the$time_until
calcs.如果我理解正确的话,你想“四舍五入”年龄吗?那么沿着这些思路怎么样:
If I understand correctly you want to "round" the age? Then how about something along these lines:
编辑:重写为使用 DateInterval
这应该可以为你解决问题。 。
Edit: rewrote to use DateInterval
This should do the trick for you...