C# 根據出生年月 計算天數/計算X歲X月X天字串
阿新 • • 發佈:2020-09-21
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() + "天"; } } } }