c#根据生日和当前日期计算年龄源代码
返回一个 整形的年龄和一个带单位的年龄
/// <summary>
/// 点击按钮测试年龄方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
int age = 0;
DateTime dt1 = new DateTime();
DateTime dt2 = new DateTime();
dt1 = DateTime.Parse("2001-01-01");
dt2 = DateTime.Parse("2020-01-01");
GetAge(dt1, dt2, ref age);
MessageBox.Show(GetAge(dt1, dt2, ref age));
MessageBox.Show(age.ToString());
}
测试结果如下:
/// <summary>
/// 根据出生日期获取年龄(不随时间变化)
/// </summary>
/// <param name="birthDay">生日</param>
/// <param name="endDate">指定的日期</param>
/// <param name="age">年龄整形</param>
/// <returns></returns>
public string GetAge(DateTime birthDay, DateTime endDate, ref int age)
{
string result = "";
if (endDate.Date.CompareTo(birthDay.Date) >= 0)
{
TimeSpan time = endDate - birthDay;
int diffYear = endDate.Year - birthDay.Year;
int diffMonth = endDate.Month - birthDay.Month;
int diffDay = endDate.Day - birthDay.Day;
int diffHour = endDate.Hour - birthDay.Hour;
int diffMinute = endDate.Minute - birthDay.Minute;
int diffSecond = endDate.Second - birthDay.Second;
//小于一天的
if (time.Days < 1)
{
if (time.Hours != 0)
{
result = time.Hours.ToString() + "时";
}
else
{
result = "1时";
}
age = 0;
return result;
}
else
{
#region 算法先将所有为负数的值变为正数
if (diffSecond < 0)
{
diffMinute = diffMinute - 1;
diffSecond = diffSecond + 60;
}
if (diffMinute < 0)
{
diffHour = diffHour - 1;
diffMinute = 60 + diffMinute;
}
if (diffHour < 0)
{
diffDay = diffDay - 1;
diffHour = 24 + diffHour;
}
if (diffDay < 0)
{
diffDay = (System.DateTime.DaysInMonth(birthDay.Year, birthDay.Month) + endDate.Day) - birthDay.Day;
diffMonth = diffMonth - 1;
}
if (diffMonth < 0)
{
diffYear = diffYear - 1;
diffMonth = diffMonth + 12;
}
#endregion
//age去年龄整数
age = diffYear;
//大于等于1天小于1月的,精确到小时;
if (diffMonth < 1 && diffYear == 0)
{
if (diffDay != 0 && diffHour != 0)
{
result = diffDay.ToString() + "天" + diffHour.ToString() + "时";
}
else if (diffDay == 0)
{
result = diffHour.ToString() + "时";
}
else if (diffHour == 0)
{
result = diffDay.ToString() + "天";
}
return result;
}//大于等于1月且小于1周岁的,精确到天;
else if (diffMonth >= 1 && diffYear == 0)
{
if (diffMonth != 0 && diffDay != 0)
{
result = diffMonth.ToString() + "月" + diffDay.ToString() + "天";
}
else if (diffDay == 0)
{
result = diffMonth.ToString() + "月";
}
return result;
}
if (diffYear >= 1 && diffYear < 3)
{
if (diffMonth != 0 && diffYear != 0)
{
result = diffYear.ToString() + "岁" + diffMonth.ToString() + "月";
}
else if (diffMonth == 0)
{
result = diffYear.ToString() + "岁";
}
return result;
}
if (diffYear >= 3)
{
result = diffYear.ToString() + "岁";
return result;
}
}
}
return result;
}
原文链接:http://www.jxszl.com/jlmb/Others/23996.html