Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Many years ago, to provide an <a href="http://cloud9.hedgee.com/age" rel="noreferrer">age calculator gimmick</a> on my website, I wrote a function to calculate age to a fraction. This is a quick port of that function to C# (from <a href="http://hedgee.svn.sourceforge.net/viewvc/hedgee/trunk/chris/ckwww/ckage.php3" rel="noreferrer">the PHP version</a>). I'm afraid I haven't been able to test the C# version, but hope you enjoy all the same!</p> <p>(Admittedly this is a bit gimmicky for the purposes of showing user profiles on Stack Overflow, but maybe readers will find some use for it. :-))</p> <pre><code>double AgeDiff(DateTime date1, DateTime date2) { double years = date2.Year - date1.Year; /* * If date2 and date1 + round(date2 - date1) are on different sides * of 29 February, then our partial year is considered to have 366 * days total, otherwise it's 365. Note that 59 is the day number * of 29 Feb. */ double fraction = 365 + (DateTime.IsLeapYear(date2.Year) &amp;&amp; date2.DayOfYear &gt;= 59 &amp;&amp; (date1.DayOfYear &lt; 59 || date1.DayOfYear &gt; date2.DayOfYear) ? 1 : 0); /* * The only really nontrivial case is if date1 is in a leap year, * and date2 is not. So let's handle the others first. */ if (DateTime.IsLeapYear(date2.Year) == DateTime.IsLeapYear(date1.Year)) return years + (date2.DayOfYear - date1.DayOfYear) / fraction; /* * If date2 is in a leap year, but date1 is not and is March or * beyond, shift up by a day. */ if (DateTime.IsLeapYear(date2.Year)) { return years + (date2.DayOfYear - date1.DayOfYear - (date1.DayOfYear &gt;= 59 ? 1 : 0)) / fraction; } /* * If date1 is not on 29 February, shift down date1 by a day if * March or later. Proceed normally. */ if (date1.DayOfYear != 59) { return years + (date2.DayOfYear - date1.DayOfYear + (date1.DayOfYear &gt; 59 ? 1 : 0)) / fraction; } /* * Okay, here date1 is on 29 February, and date2 is not on a leap * year. What to do now? On 28 Feb in date2's year, the ``age'' * should be just shy of a whole number, and on 1 Mar should be * just over. Perhaps the easiest way is to a point halfway * between those two: 58.5. */ return years + (date2.DayOfYear - 58.5) / fraction; } </code></pre>
 

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