C#で人の年齢を計算するには?

ある人の誕生日を表すDateTimeが与えられた場合、その人の年齢を年単位で計算するにはどうすればよいですか?

ソリューション

わかりやすく、シンプルなソリューションです。

// Save today's date.
var today = DateTime.Today;
// Calculate the age.
var age = today.Year - birthdate.Year;
// Go back to the year the person was born in case of a leap year
if (birthdate.Date > today.AddYears(-age)) age--;

ただし、これはあなたが年齢の西洋的な考え方を求めていて、東アジアの計算を使っていないことを前提としています。

解説 (34)

私が作ったものではありませんが、ウェブで見つけた別の機能を少しだけ改良しました。

public static int GetAge(DateTime birthDate)
{
    DateTime n = DateTime.Now; // To avoid a race condition around midnight
    int age = n.Year - birthDate.Year;

    if (n.Month < birthDate.Month || (n.Month == birthDate.Month && n.Day < birthDate.Day))
        age--;

    return age;
}

ただ、2つのことが頭に浮かびました。グレゴリオ暦を使っていない国の人はどうするのか?DateTime.Nowは、サーバー固有の文化だと思います。実際にアジアのカレンダーを扱う知識は全くなく、カレンダー間で日付を変換する簡単な方法があるかどうかもわかりませんが、念のため、4660年から来た中国の人たちのことを考えてみてください :-)。

解説 (1)

うるう年やその他の理由で、私が知っている最良の方法は

DateTime birthDate = new DateTime(2000,3,1);
int age = (int)Math.Floor((DateTime.Now - birthDate).TotalDays / 365.25D);

お役に立てれば幸いです。

解説 (0)