确切的年龄计算

时间:2020-03-05 18:41:14  来源:igfitidea点击:
Possible Duplicate:

  How do I calculate someone's age in C#?

也许这可能很愚蠢,但我的年龄没有问题,但有时可以计算出某人的确切年龄,我在我的个人资料中介绍了我的生日(01/12/1975) ",计算得出的年龄是33岁,而我实际上仍然是32岁,要计算出确切年龄更好吗?

可能是

DateTime dt1 = DateTime.Now;
TimeSpan dt2;
dt2 = dt1.Subtract(new DateTime(1975, 12, 01));
double year = dt2.TotalDays / 365;

年度的结果是32.77405678074

这段代码可以吗?

解决方案

回答

Maybe this could be silly but and I don't have issues with my age but sometimes it is good to calculate the exact age of someone, I have introduced my birthdate in my profile (01/12/1975) "dd/mm/yyyy" and it calculated 33 and I'm 32 actually still, doesn't it better to calculate the exact age?

我的猜测是这是一个本地化问题,尽管我不知道它将如何发生,因为(至少对我而言)个人资料已以" YYYY / MM / DD"格式填写年龄。但是生日是在美国传统设置中被视为有效日期(1月12日)的生日,因此这是我要研究的区域。我也是于1975年出生,下个月是我的生日,年龄适中。

回答

实际上,由于leap年,代码将关闭。由于timespan对象没有TotalYears属性,因此获取它的最佳方法是

赦免VB.Net

Dim myAge AS Integer = DateTime.Now.year - BirthDate.year
If Birthdate.month < DateTime.Now.Month _
OrElse BirthDate.Month = DateTime.Now.Month AndAlso Birthdate.Day < DateTime.Now.Day Then
MyAge -= 1
END IF

回答

如果我们出生于1975年1月12日,那么今天我们已经33岁。

如果我们是1975年12月1日出生的,那么我们今天32岁。

如果我们在编辑个人资料时在生日字段旁阅读了便条,便会看到" YYYY / MM / DD",我相信它会尝试解释其他格式的日期,但看起来像是在解释MM / DD / YYYY(美国标准日期)优先于DD / MM / YYYY(欧洲标准日期)。简单的解决方法是根据建议的输入样式输入生日。