Search code examples
javascriptdateleap-year

JavaScript calculate years and days from start date


I have date when someone is born, and I need to calculate with JavaScript or jQuery or so, how many years, days since birth date, until now.

So result can be like 20 years, 89 days.

I need to have same results as Wikipedia does with their function of "age in years", as it takes leap years in account and what not. So far I got code that works, but in some cases makes mistake of 1 day. My function is:

function DateDiff(date1, date2){
var res=((date1.getTime() - date2.getTime())/1000/60/60/24)-offset_d;
var full_days=Math.floor(res/365.25);
var f1=Math.round((res%365.25))
return  full_days + " years, " +f1 +  " days" ; }

Thanks for your help, I am doing this for days.


Solution

  • You could roll your own... but I would highly recommend something like Moment.js. It is a solid library that has been proven in the field for calculating Math like this. It is only 4k, so I think you will be fine on size also.