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;
    }

 

相关文章:

  • 2021-12-04
  • 2021-07-22
  • 2021-11-16
  • 2022-12-23
  • 2022-12-23
  • 2021-12-02
  • 2021-11-30
  • 2022-03-09
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-30
相关资源
相似解决方案