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 }