C# 根据出生年月 计算天数/计算X岁X月X天字符串
public class TimeTool
{
//根据出生年月计算 整数天
private static int GetAgeByBirthdate(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;
} //根据出生年月计算 X岁或X月X天或X天
public static string GetAgeByBirthday(DateTime birthday)
{
var currenttime = DateTime.Now;
var diffTime = currenttime - birthday;
if (diffTime.TotalDays >= 365)
{
//年龄计算
return GetAgeByBirthdate(birthday).ToString() + "岁";
}
else
{
//个月计算
var diffmonth = currenttime.Month - birthday.Month;
var day = currenttime.Day - birthday.Day;
if (day < 0)
{
diffmonth--;
}
if (diffmonth > 0)
{
DateTime newbirthday = birthday.AddMonths(diffmonth);
day = (int)((currenttime - newbirthday).TotalDays);
return diffmonth.ToString() + "个月" + (day == 0 ? "" : day.ToString() + "天");
}
else
{
//直接计算天
return ((int)(diffTime.TotalDays)).ToString() + "天";
}
}
}
}
本文来自博客园,作者:jevan,转载请注明原文链接:https://www.cnblogs.com/DoNetCShap/p/13707221.html

浙公网安备 33010602011771号