我如何计算一个人的年,月,日的年龄是多少? [英] How can I calculate the age of a person in year, month, days?

查看:375
本文介绍了我如何计算一个人的年,月,日的年龄是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

欲计算给定的出生日期和当前日期在相对于当前日期的年,月和天的人的年龄。

I want to calculate the age of a person given the date of birth and the current date in years, months and days relative to the current date.

例如:

>>> calculate_age(2008, 01, 01)
1 years, 0 months, 16 days

任何指针算法,它是将AP preciated。

Any pointer to an algorithm that does that will be appreciated.

推荐答案

首先,请注意,如果,例如,你出生于2月1日,然后在下面的3月1日,你正好1个月大,即使假设在几天的年龄只有28 - 比一般月份的长度较少。年也有可变长度(由于闰年),这意味着你的年龄在你的生日通常不是几年一个确切的整数。如果你想给前preSS的时候,你已经在年/月/日活着的确切数额,看到我的其他的答案。但更可能你要恰到好处,让出生于2月1日表示,每次2月1日你是X年,0个月,0日龄,并在每月的第一个你是X年,Y月做傻事吧, 0天。

First, note the assumption that if, for example, you were born on February 1st then on the following March 1st, you are exactly 1 month old, even though your age in days is only 28 -- less than the length of an average month. Years also have variable length (due to leap years) which means your age on your birthday is usually not an exact integer number of years. If you want to express the exact amount of time you've been alive in years/months/days, see my other answer. But more likely you want to fudge it just right so that being born on February 1st means that every February 1st you are X years, 0 months, and 0 days old, and on the 1st of any month you are X years, Y months, and 0 days.

在这种情况下,请继续阅读。 (注:以下仅适用于过去的日期)

In that case, read on. (NB: the following only works for dates in the past.)

由于出生日期,(Y,M,D),当前日期,(ynow,mnow,dnow),和一个函数 TM(),让 UNIX /出现时间为给定的日期时,下面将输出一个3元素列表,给出年龄为{年,月,日}

Given a date of birth, (y,m,d), the current date, (ynow,mnow,dnow), and a function tm() that gives unix/epoch time for a given date, the following will output a 3-element list giving age as {years, months, days}:

t0 = y*12 + m - 1;        # total months for birthdate.
t = ynow*12 + mnow - 1;   # total months for Now.
dm = t - t0;              # delta months.    
if(dnow >= d) return [floor(dm/12), mod(dm,12), dnow-d];
dm--; t--;
return [floor(dm/12), mod(dm,12), 
        (tm({ynow,mnow,dnow}) - tm({floor(t/12), mod(t,12)+1, d}))/60/60/24];

以下是如果你不喜欢所有的地板和MODS的等价算法。但是,我觉得上面的比较好。一方面它避免调用 TM()时,它并不需要。

{yl, ml} = {ynow, mnow};
if(mnow < m || mnow == m && dnow < d) yl--;
if(dnow < d) ml--;
years = yl - y;
months = ml + 12*(ynow - yl) - m;
yl = ynow;
if(ml == 0) { ml = 12; yl--; }
days = (tm({ynow, mnow, dnow}) - tm({yl, ml, d}))/60/60/24;
return [years, months, days];

这篇关于我如何计算一个人的年,月,日的年龄是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆