C#根据出生日期和当前日期计算精确年龄的代码

代码过程,将开发过程比较常用的一些代码段做个备份,如下的资料是关于C#根据出生日期和当前日期计算精确年龄的代码,应该对小伙伴们有所用处。

public static string GetAge(DateTime dtBirthday, DateTime dtNow) {

        if (DataType.DateTime_IsNull(ref dtBirthday) == true)
        {
            return string.Empty;
        }
        
        intDay = dtNow.Day - dtBirthday.Day;
        if (intDay < 0)
        {
            dtNow = dtNow.AddMonths(-1);
            intDay += DateTime.DaysInMonth(dtNow.Year, dtNow.Month);
        }
        
        intMonth = dtNow.Month - dtBirthday.Month;
        if (intMonth < 0)
        {
            intMonth += 12;
            dtNow = dtNow.AddYears(-1);
        }
        
        intYear = dtNow.Year - dtBirthday.Year;
        
        {
            strAge = intYear.ToString() + "岁";
        }
        
        {
            strAge += intMonth.ToString() + "月";
        }
        
        {
            if (strAge.Length == 0 || intDay > 0)
            {
                strAge += intDay.ToString() + "日";
            }
        }
        
        return strAge;
    }
复制代码

你可能感兴趣的:(C#根据出生日期和当前日期计算精确年龄的代码)