生年月日から今日までのC#の年齢を計算する方法(正確には天まで)

11882 ワード

C#年齢の計算方法、自分で1つのとてもぼろぼろなことを書いて、計算はそんなに正確ではないべきで、バックアップ /// /// /// /// /// /// public static string GetAgeYDM(DateTime birthday, DateTime now) { string ts = ""; int day = System.Threading.Thread.CurrentThread.CurrentUICulture.Calendar.GetDaysInMonth(birthday.Year, birthday.Month); int mon = 0; var age = now.Year - birthday.Year; if (now.Month < birthday.Month) { age--; if (now.Day < birthday.Day) { day = day - birthday.Day + now.Day; mon = 12 - birthday.Month + now.Month - 1; } else { day = now.Day - birthday.Day; mon = 12 - birthday.Month + now.Month; } } if (now.Month == birthday.Month) { if (now.Day < birthday.Day) { age--; day = day - birthday.Day + now.Day; mon = 12 - birthday.Month + now.Month - 1; } else { day = now.Day - birthday.Day; } } if (now.Month > birthday.Month) { if (now.Day < birthday.Day) { mon = now.Month - 1 - birthday.Month; day = day - birthday.Day + now.Day; } else { mon = now.Month - birthday.Month; day = now.Day - birthday.Day; } } if (age < 6 && age >=0) { if (age != 0) { ts = ts + age + " "; } if (mon != 0) { ts = ts + mon + " "; } if (day != 0) { ts = ts + day + " "; } return ts; } else if (age < 0) { return " :"+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); } else { return age + " "; } }