C# 通过生日计算年龄,精确到天


      //搞一个静态方法  
      public static class Extension
      {
          public static int GetAgeByBirthdate(this 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;
         }
      }

  

       //再附一个身份证号取年龄的方法
        public static DateTime IdCardtoDate(this string cardno)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(cardno) || cardno.Length != 18)
                {
                    return new DateTime(2099, 1, 1);
                }
                else
                {
                    int year = Convert.ToInt32(cardno.Substring(6, 4));
                    int month = Convert.ToInt32(cardno.Substring(10, 2));
                    int day = Convert.ToInt32(cardno.Substring(12, 2));
                    return new DateTime(year, month, day);
                }
            }
            catch
            {
                return new DateTime(2099, 1, 1);
            }
        }

  

        //调用就简单一些了
        string idCardNumber = "11122219991201XXXX";
        int age = idCardNumber.IdCardtoDate().GetAgeByBirthdate();

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM