Loading

C# 根据出生年月 计算天数/计算X岁X月X天字符串

public class TimeTool
    {
        //根据出生年月计算 整数天
        private static int GetAgeByBirthdate(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;
        }           //根据出生年月计算 X岁或X月X天或X天
        public static string GetAgeByBirthday(DateTime birthday)
        {
            var currenttime = DateTime.Now;
            var diffTime = currenttime - birthday;
            if (diffTime.TotalDays >= 365)
            {
                //年龄计算
                return GetAgeByBirthdate(birthday).ToString() + "岁";
            }
            else
            {
                //个月计算
                var diffmonth = currenttime.Month - birthday.Month;
                var day = currenttime.Day - birthday.Day;
                if (day < 0)
                {
                    diffmonth--;
                }
                if (diffmonth > 0)
                {
                    DateTime newbirthday = birthday.AddMonths(diffmonth);
                    day = (int)((currenttime - newbirthday).TotalDays);
                    return diffmonth.ToString() + "个月" + (day == 0 ? "" : day.ToString() + "天");
                }
                else
                {
                    //直接计算天
                    return ((int)(diffTime.TotalDays)).ToString() + "天";
                }
            }

        }
    }

  

posted @ 2020-09-21 18:29  jevan  阅读(229)  评论(0编辑  收藏  举报