Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your <code>diff</code> calculation will give you the number of days between the two dates. It will take into account leap years, so over exactly 4 years it will yield <code>(365 * 4) + 1</code> days. </p> <p>It will also count partial days so if the <code>date</code> parameter is noon yesterday and today it is 6am then <code>diff</code> will be <code>0.75</code>. </p> <p>How you convert from days to years is up to you. Using 365, 365.242, or 365.25 days per year all are reasonable in the abstract. However, since you are calculating people's ages according to their birthdays, I would do it like this <a href="http://jsfiddle.net/OldPro/hKyBM/" rel="nofollow">http://jsfiddle.net/OldPro/hKyBM/</a> :</p> <pre><code>function noon(date) { // normalize date to noon that day return new Date(date.getFullYear(), date.getMonth(), date.getDate(), 12, 0, 0, 0); } // Takes a Date function getAge(date) { var now = noon(new Date()), birthday = noon(date), thisBirthday = new Date(birthday), prevBirthday, nextBirthday, years, partYear, msInYear; thisBirthday.setFullYear(now.getFullYear()); if (thisBirthday &gt; now) { // not reached birthday this year nextBirthday = thisBirthday; prevBirthday = new Date(thisBirthday); prevBirthday.setFullYear(now.getFullYear() - 1); } else { nextBirthday = new Date(thisBirthday); nextBirthday.setFullYear(now.getFullYear() + 1); prevBirthday = thisBirthday; } years = prevBirthday.getFullYear() - birthday.getFullYear(); msInYear = nextBirthday - prevBirthday; partYear = (now - prevBirthday) / msInYear; return years + partYear } </code></pre> <p>In other words, I compute the fractional year as number of days since the last birthday divided by the number of days between the previous birthday and the next birthday. I think that is how most people think of birthdays and years.</p> <p>Note: You can get into trouble with timezones when converting date strings to Dates. Short ISO 8601 dates like '2013-05-14' are interpreted as midnight UTC which makes that date May 13, not May 14 in the US and everywhere else with negative UTC offsets. So be careful.</p>
 

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