在 C# 中,如何根据 DateTime 类型的生日计算某人的年龄?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In C#, how do I calculate someone's age based on a DateTime type birthday?
提问by Jeff Atwood
Given a DateTime
representing a person's birthday, how do I calculate their age in years?
鉴于DateTime
代表一个人的生日,我如何计算他们的年龄(以年为单位)?
采纳答案by Mike Polen
An easy to understand and simple solution.
一个易于理解和简单的解决方案。
// Save today's date.
var today = DateTime.Today;
// Calculate the age.
var age = today.Year - birthdate.Year;
// Go back to the year the person was born in case of a leap year
if (birthdate.Date > today.AddYears(-age)) age--;
However, this assumes you are looking for the westernidea of age and not using East Asian reckoning.
但是,这假设您正在寻找西方的年龄概念,而不是使用东亚计算。
回答by Nick Berardi
The best way that I know of because of leap years and everything is:
由于闰年和一切,我所知道的最好的方法是:
DateTime birthDate = new DateTime(2000,3,1);
int age = (int)Math.Floor((DateTime.Now - birthDate).TotalDays / 365.25D);
回答by Michael Stum
Another function, not by me but found on the web and refined it a bit:
另一个功能,不是我的,而是在网上找到的,并稍微改进了一下:
public static int GetAge(DateTime birthDate)
{
DateTime n = DateTime.Now; // To avoid a race condition around midnight
int age = n.Year - birthDate.Year;
if (n.Month < birthDate.Month || (n.Month == birthDate.Month && n.Day < birthDate.Day))
age--;
return age;
}
Just two things that come into my mind: What about people from countries that do not use the Gregorian calendar? DateTime.Now is in the server-specific culture I think. I have absolutely zero knowledge about actually working with Asian calendars and I do not know if there is an easy way to convert dates between calendars, but just in case you're wondering about those Chinese guys from the year 4660 :-)
我想到了两件事:来自不使用公历的国家的人呢?我认为 DateTime.Now 处于特定于服务器的文化中。我对实际使用亚洲日历的知识完全为零,我不知道是否有一种简单的方法可以在日历之间转换日期,但以防万一你想知道 4660 年的那些中国人:-)
回答by David Wengier
This is the version we use here. It works, and it's fairly simple. It's the same idea as Jeff's but I think it's a little clearer because it separates out the logic for subtracting one, so it's a little easier to understand.
这是我们在这里使用的版本。它有效,而且相当简单。这和 Jeff 的想法是一样的,但我认为它更清晰一些,因为它分离了减一的逻辑,所以更容易理解。
public static int GetAge(this DateTime dateOfBirth, DateTime dateAsAt)
{
return dateAsAt.Year - dateOfBirth.Year - (dateOfBirth.DayOfYear < dateAsAt.DayOfYear ? 0 : 1);
}
You could expand the ternary operator to make it even clearer, if you think that sort of thing is unclear.
如果您认为这种事情不清楚,您可以扩展三元运算符以使其更加清晰。
Obviously this is done as an extension method on DateTime
, but clearly you can grab that one line of code that does the work and put it anywhere. Here we have another overload of the Extension method that passes in DateTime.Now
, just for completeness.
显然,这是作为 上的扩展方法完成的DateTime
,但很明显,您可以获取完成工作的那一行代码并将其放在任何地方。这里我们有另一个传入的 Extension 方法的重载DateTime.Now
,只是为了完整性。
回答by ScArcher2
This is a strange way to do it, but if you format the date to yyyymmdd
and subtract the date of birth from the current date then drop the last 4 digits you've got the age :)
这是一种奇怪的方法,但是如果您将日期格式化为yyyymmdd
并从当前日期中减去出生日期,然后删除您的年龄的最后 4 位数字 :)
I don't know C#, but I believe this will work in any language.
我不懂 C#,但我相信这适用于任何语言。
20080814 - 19800703 = 280111
Drop the last 4 digits = 28
.
去掉最后 4 位数字 = 28
。
C# Code:
C# 代码:
int now = int.Parse(DateTime.Now.ToString("yyyyMMdd"));
int dob = int.Parse(dateOfBirth.ToString("yyyyMMdd"));
int age = (now - dob) / 10000;
Or alternatively without all the type conversion in the form of an extension method. Error checking omitted:
或者也可以不用所有类型转换的扩展方法的形式。省略错误检查:
public static Int32 GetAge(this DateTime dateOfBirth)
{
var today = DateTime.Today;
var a = (today.Year * 100 + today.Month) * 100 + today.Day;
var b = (dateOfBirth.Year * 100 + dateOfBirth.Month) * 100 + dateOfBirth.Day;
return (a - b) / 10000;
}
回答by user2601
I have created a SQL Server User Defined Function to calculate someone's age, given their birthdate. This is useful when you need it as part of a query:
我创建了一个 SQL Server 用户定义函数来计算某人的年龄,给定他们的生日。当您需要它作为查询的一部分时,这很有用:
using System;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
public partial class UserDefinedFunctions
{
[SqlFunction(DataAccess = DataAccessKind.Read)]
public static SqlInt32 CalculateAge(string strBirthDate)
{
DateTime dtBirthDate = new DateTime();
dtBirthDate = Convert.ToDateTime(strBirthDate);
DateTime dtToday = DateTime.Now;
// get the difference in years
int years = dtToday.Year - dtBirthDate.Year;
// subtract another year if we're before the
// birth day in the current year
if (dtToday.Month < dtBirthDate.Month || (dtToday.Month == dtBirthDate.Month && dtToday.Day < dtBirthDate.Day))
years=years-1;
int intCustomerAge = years;
return intCustomerAge;
}
};
回答by user2601
I think the TimeSpan has all that we need in it, without having to resort to 365.25 (or any other approximation). Expanding on Aug's example:
我认为 TimeSpan 拥有我们需要的一切,而不必求助于 365.25(或任何其他近似值)。扩展八月的例子:
DateTime myBD = new DateTime(1980, 10, 10);
TimeSpan difference = DateTime.Now.Subtract(myBD);
textBox1.Text = difference.Years + " years " + difference.Months + " Months " + difference.Days + " days";
回答by James Curran
My suggestion
我的建议
int age = (int) ((DateTime.Now - bday).TotalDays/365.242199);
That seems to have the year changing on the right date. (I spot tested up to age 107.)
这似乎在正确的日期改变了年份。(我现场测试到 107 岁。)
回答by James Curran
I've spent some time working on this and came up with this to calculate someone's age in years, months and days. I've tested against the Feb 29th problem and leap years and it seems to work, I'd appreciate any feedback:
我花了一些时间研究这个,并想出了这个来计算某人的年龄(以年、月和日为单位)。我已经针对 2 月 29 日的问题和闰年进行了测试,它似乎有效,我希望得到任何反馈:
public void LoopAge(DateTime myDOB, DateTime FutureDate)
{
int years = 0;
int months = 0;
int days = 0;
DateTime tmpMyDOB = new DateTime(myDOB.Year, myDOB.Month, 1);
DateTime tmpFutureDate = new DateTime(FutureDate.Year, FutureDate.Month, 1);
while (tmpMyDOB.AddYears(years).AddMonths(months) < tmpFutureDate)
{
months++;
if (months > 12)
{
years++;
months = months - 12;
}
}
if (FutureDate.Day >= myDOB.Day)
{
days = days + FutureDate.Day - myDOB.Day;
}
else
{
months--;
if (months < 0)
{
years--;
months = months + 12;
}
days +=
DateTime.DaysInMonth(
FutureDate.AddMonths(-1).Year, FutureDate.AddMonths(-1).Month
) + FutureDate.Day - myDOB.Day;
}
//add an extra day if the dob is a leap day
if (DateTime.IsLeapYear(myDOB.Year) && myDOB.Month == 2 && myDOB.Day == 29)
{
//but only if the future date is less than 1st March
if (FutureDate >= new DateTime(FutureDate.Year, 3, 1))
days++;
}
}
回答by SillyMonkey
Here's a one-liner:
这是一个单行:
int age = new DateTime(DateTime.Now.Subtract(birthday).Ticks).Year-1;