c#实现通过出生日期计算岁,月,天

   /// 通过生日和当前日期计算岁,月,天

        ///

        /// 生日

        /// 当前日期

        ///

        ///

        ///

        private void GetAgeByBirthday(DateTime birthday, DateTime now,out int year,out int month,

        out int day)

        {

            //生日的年,月,日

            int birthdayYear = birthday.Year;

            int birthdayMonth = birthday.Month;

            int birthdayDay = birthday.Day;

 

            //当前时间的年,,

 

            int nowYear = now.Year;

            int nowMonth = now.Month;

            int nowDay = now.Day;

 

            //得到天

            if (nowDay >= birthdayDay)

            {

                day = nowDay - birthdayDay;

            }

            else

            {

                nowMonth -= 1;

                day = GetDay(nowMonth, nowYear) + nowDay - birthdayDay;

            }

 

            //得到月

            if (nowMonth >= birthdayMonth)

            {

                month = nowMonth - birthdayMonth;

            }

            else

            {

                nowYear -= 1;

                month = 12 + nowMonth - birthdayMonth;

            }

 

            //得到年

            year = nowYear - birthdayYear;

        }

 

        ///

        /// 获取天数

        ///

        private int GetDay(int month, int year)

        {

            int day = 0;

            switch (month)

            {

                case 1:

                case 3:

                case 5:

                case 7:

                case 8:

                case 10:

                case 12:

                    day = 31;

                    break;

                case 2:

                    //闰年天,平年天

                    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)

                    {

                        day = 29;

                    }

                    else

                    {

                        day = 28;

                    }

                    break;

                case 4:

                case 6:

                case 9:

                case 11:

                    day = 30;

                    break;

            }

            return day;

         }

你可能感兴趣的:(c#)