C# 根據生日獲取年齡


C# 根據生日獲取年齡

    根據生日計算出准確的年齡,不等於0時,返回的是歲,等於0時,返回的是天(以‘-’來區分)

 

public static string GetAgeByBirth(string Birthdate)
    {
        string ages = string.Empty;
        try
        {
            //年齡格式化
            DateTimeFormatInfo dtFormat = new DateTimeFormatInfo();
            dtFormat.ShortDatePattern = "yyyy-MM-dd";
            DateTime dt = Convert.ToDateTime(Birthdate, dtFormat);
            int age = DateTime.Now.Year - dt.Year;
            if (DateTime.Now.Month < dt.Month || (DateTime.Now.Month == dt.Month && DateTime.Now.Day < dt.Day)) age--;
            TimeSpan ts = DateTime.Now - dt;
            ages = age == 0 ? "-" + ts.Days : age.ToString();
        }
        catch(Exception ex)
        {
            BuildLogFile(ex.Message);
        }
        
        return ages;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM