1. 程式人生 > >根據DateTime計算年齡

根據DateTime計算年齡

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime begin = new DateTime(1996, 10, 23);
            DateTime end = new DateTime(2018, 9, 27);
            Console.WriteLine(calculationDate(begin, end));
            Console.ReadKey();
        }

        public static string calculationDate(DateTime beginDateTime, DateTime endDateTime)
        {
            if (beginDateTime > endDateTime)
            {
                return "開始時間應小於或等與結束時間!";
            }

            // 計算出生日期到當前日期總月數
            int Months = endDateTime.Month - beginDateTime.Month + 12 * (endDateTime.Year - beginDateTime.Year);
            // 出生日期加總月數後,如果大於當前日期則減一個月
            int totalMonth = (beginDateTime.AddMonths(Months) > endDateTime) ? Months - 1 : Months;
            // 計算整年
            int fullYear = totalMonth / 12;
            // 計算整月
            int fullMonth = totalMonth % 12;
            // 計算天數
            DateTime changeDate = beginDateTime.AddMonths(totalMonth);
            double days = (endDateTime - changeDate).TotalDays;

            string returnStr = "";
            if(fullYear > 0)
            {
                returnStr += fullYear + "歲";
            }
            if(fullMonth > 0)
            {
                returnStr += fullMonth + "月";
            }
            if (days > 0)
            {
                returnStr += days + "天";
            }
            
            return returnStr;
        }
    }
}