//搞一个静态方法
public static class Extension
{
public static int GetAgeByBirthdate(this DateTime birthdate)
{
DateTime now = DateTime.Now;
int age = now.Year - birthdate.Year;
if (now.Month < birthdate.Month || (now.Month == birthdate.Month && now.Day < birthdate.Day))
{
age--;
}
return age < 0 ? 0 : age;
}
}
//再附一个身份证号取年龄的方法
public static DateTime IdCardtoDate(this string cardno)
{
try
{
if (string.IsNullOrWhiteSpace(cardno) || cardno.Length != 18)
{
return new DateTime(2099, 1, 1);
}
else
{
int year = Convert.ToInt32(cardno.Substring(6, 4));
int month = Convert.ToInt32(cardno.Substring(10, 2));
int day = Convert.ToInt32(cardno.Substring(12, 2));
return new DateTime(year, month, day);
}
}
catch
{
return new DateTime(2099, 1, 1);
}
}
//调用就简单一些了
string idCardNumber = "11122219991201XXXX";
int age = idCardNumber.IdCardtoDate().GetAgeByBirthdate();