首页 > 技术文章 > C#获取年龄段 几零后

ericli-ericli 2015-11-18 10:50 原文

/// <summary>
        /// 根据年龄获得年龄段
        /// </summary>
        /// <param name="age"></param>
        /// <returns></returns>
        public static string GetAgeRange(int age)
        {
            int year = DateTime.Now.Year - age;
            if (year <= 1900 || year > DateTime.Now.Year)
            {
                return "";
            }
            string thirdNum= year.ToString().Substring(2, 1);
            string fourthNum = year.ToString().Substring(3, 1);

            if (int.Parse(fourthNum) >= 5)
            {
                return string.Format("{0}{1}后", thirdNum, "5");
            }
            else
            {
                return string.Format("{0}{1}后", thirdNum, "0");
            }
        }
        /// <summary>
        /// 根据身份证获得年龄段
        /// </summary>
        /// <param name="IDCard"></param>
        /// <returns></returns>
        public static string GetAgeRange(string IDCard)
        {
            DateTime birth = ValidatHelper.GetBirthByIDCard(IDCard);
            string year = birth.Year.ToString().PadLeft(4, '0');
            string thirdNum= year.ToString().Substring(2, 1);
            string fourthNum= year.ToString().Substring(3, 1);

            if (int.Parse(y2) >= 5)
            {
                return string.Format("{0}{1}后", thirdNum, "5");
            }
            else
            {
                return string.Format("{0}{1}后", thirdNum, "0");
            }
        }
        #region 通过身份证号获得出生日期
        public static DateTime GetBirthByIDCard(string IDCard)
        {
            if (!CheckIDCard(IDCard))
            {
                return DateTime.MinValue.Date;
            }
            string birth = "";
            if (IDCard.Length == 18)
            {
                birth = IDCard.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            }
            else if (IDCard.Length == 15)
            {
                birth = IDCard.Substring(6, 6).Insert(4, "-").Insert(2, "-");
            }
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == true)
            {
                return time;
            }
            else
            {
                return DateTime.MinValue.Date;
            }
        }
        #endregion

 

推荐阅读