Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>2 Main problems to solve are:</p> <p><strong>1. Calculate Exact age</strong> - in years, months, days, etc.</p> <p><strong>2. Calculate Generally perceived age</strong> - people usually do not care how old they exactly are, they just care when their birthday in the current year is.</p> <hr> <p>Solution for <strong>1</strong> is obvious:</p> <pre><code>DateTime birth = DateTime.Parse("1.1.2000"); DateTime today = DateTime.Today; //we usually don't care about birth time TimeSpan age = today - birth; //.NET FCL should guarantee this as precise double ageInDays = age.TotalDays; //total number of days ... also precise double daysInYear = 365.2425; //statistical value for 400 years double ageInYears = ageInDays / daysInYear; //can be shifted ... not so precise </code></pre> <hr> <p>Solution for <strong>2</strong> is the one which is not so precise in determing total age, but is perceived as precise by people. People also usually use it, when they calculate their age "manually":</p> <pre><code>DateTime birth = DateTime.Parse("1.1.2000"); DateTime today = DateTime.Today; int age = today.Year - birth.Year; //people perceive their age in years if (today.Month &lt; birth.Month || ((today.Month == birth.Month) &amp;&amp; (today.Day &lt; birth.Day))) { age--; //birthday in current year not yet reached, we are 1 year younger ;) //+ no birthday for 29.2. guys ... sorry, just wrong date for birth } </code></pre> <p>Notes to 2.:</p> <ul> <li>This is my preferred solution</li> <li>We cannot use DateTime.DayOfYear or TimeSpans, as they shift number of days in leap years</li> <li>I have put there little more lines for readability</li> </ul> <p>Just one more note ... I would create 2 static overloaded methods for it, one for universal usage, second for usage-friendliness:</p> <pre><code>public static int GetAge(DateTime bithDay, DateTime today) { //chosen solution method body } public static int GetAge(DateTime birthDay) { return GetAge(birthDay, DateTime.Now); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload