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