C# 根據出生年月 計算天數/計算X歲X月X天字元串

 1     public class TimeTool
 2     {
 3         //根據出生年月計算 整數天
 4         private static int GetAgeByBirthdate(DateTime birthdate)
 5         {
 6             DateTime now = DateTime.Now;
 7             int age = now.Year - birthdate.Year;
 8             if (now.Month < birthdate.Month || (now.Month == birthdate.Month && now.Day < birthdate.Day))
 9             {
10                 age--;
11             }
12             return age < 0 ? 0 : age;
13         }
//根據出生年月計算 X歲或X月X天或X天
14 public static string GetAgeByBirthday(DateTime birthday) 15 { 16 var currenttime = DateTime.Now; 17 var diffTime = currenttime - birthday; 18 if (diffTime.TotalDays >= 365) 19 { 20 //年齡計算 21 return GetAgeByBirthdate(birthday).ToString() + ""; 22 } 23 else 24 { 25 //個月計算 26 var diffmonth = currenttime.Month - birthday.Month; 27 var day = currenttime.Day - birthday.Day; 28 if (day < 0) 29 { 30 diffmonth--; 31 } 32 if (diffmonth > 0) 33 { 34 DateTime newbirthday = birthday.AddMonths(diffmonth); 35 day = (int)((currenttime - newbirthday).TotalDays); 36 return diffmonth.ToString() + "個月" + (day == 0 ? "" : day.ToString() + ""); 37 } 38 else 39 { 40 //直接計算天 41 return ((int)(diffTime.TotalDays)).ToString() + ""; 42 } 43 } 44 45 } 46 }