C#&.NET程序开发中根据已知的生日日期怎样计算某人的年龄呢?
4 个回答
-
使用C#创建的两种计算年龄的方法,代码如下:
public int CalculateAge1(DateTime birthDate, DateTime now) { int age = now.Year - birthDate.Year; if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day)) age--; return age; } public int CalculateAge2(DateTime birthDate, DateTime now) { int age = now.Year - birthDate.Year; if (birthDate > now.AddYears(-age)) age--; return age; }
-
或者创建一个C#的静态扩展方法,代码如下:
public static class DateTimeExtensions { public static int Age(this DateTime birthDate) { return Age(birthDate, DateTime.Now); } public static int Age(this DateTime birthDate, DateTime offsetDate) { int result=0; result = offsetDate.Year - birthDate.Year; if (offsetDate.DayOfYear < birthDate.DayOfYear) { result--; } return result; } }
-
以下是一个可以计算出多少天在内的年龄的方法,代码如下:
public static string HowOld(DateTime birthday, DateTime now) { if (now < birthday) throw new ArgumentOutOfRangeException("生日必须小于参照日期."); TimeSpan diff = now - birthday; int diffDays = (int)diff.TotalDays; if (diffDays > 7) { int age = now.Year - birthday.Year; if (birthday > now.AddYears(-age)) age--; if (age > 0) { return age + " 岁"; } else { DateTime d = birthday; int diffMonth = 1; while (d.AddMonths(diffMonth) <= now) { diffMonth++; } age = diffMonth-1; if (age == 1 && d.Day > now.Day) age--; if (age > 0) { return age + "个月"; } else { age = diffDays / 7; return age + "周"; } } } else if (diffDays > 0) { int age = diffDays; return age + "天"; } else { int age = diffDays; return "刚出生"; } }