I have been working with a lot of Date objects recently and have had fun over the years doing math to figure out an age using years, months and days of the Date objects.
We all know you can declare a new date and get these properties by something like this:
let now = new Date();
console.log(now.getMonth() + 1);
//or
console.log(now.getFullYear());
we also know that you could declare a date for a set instance in history such as:
let birth = new Date(1963, 9, 17);
granted we have all probably written or used pre-made tools to determine ages. As anyone who has done this before knows, it can get complicated with leap years and converting -1 year and 1 month
to 11 months
. PLEASE NOTE, i know we can getTime()
and easily subtract milliseconds, but then you have to convert to standard date format, so that can be just as complicated as using the year, month and day.
Does JavaScript have anything built in that will give me the age in years, months and days?
i have tried .toLocaleDateString()
, .UTC()
and .valueOf()
on the DIFFERENCES between date objects (aka Ages) and am not getting results (just NaN).
thanks!