Why, when subtracting two dates of type DateTime is a value of type TimeSpan produced, and how do I get a result of type DateTime from here?
public int Age() { return (DateTime.Now - BirthDate) } Why, when subtracting two dates of type DateTime is a value of type TimeSpan produced, and how do I get a result of type DateTime from here?
public int Age() { return (DateTime.Now - BirthDate) } The difference between dates cannot be translated into years, because each calendar year has its own number of days. Those. the difference of 365 days can be either a full year or incomplete, depending on the date of reference.
So you have to compare the year and date manually:
public static int GetAge(DateTime birthDate) { var now = DateTime.Today; return now.Year - birthDate.Year - 1 + ((now.Month > birthDate.Month || now.Month == birthDate.Month && now.Day >= birthDate.Day) ? 1 : 0); } More beautiful solution from Mike Polen:
DateTime now = DateTime.Today; int age = now.Year - bday.Year; if (bday > now.AddYears(-age)) age--; For the same reason — different lengths of the year — you cannot simply add the number of days / ticks / to some base date (for example, 01.01.0001) and use the value obtained as the age.
Such a solution may seem convenient and simple, but, unfortunately, it will give incorrect results in fairly trivial cases.
Source: https://ru.stackoverflow.com/questions/669870/
All Articles