0

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!

sao
  • 1,835
  • 6
  • 21
  • 40
  • Like you said, using miliseconds and substracts? What's the matter with it? – Thanh Trung Nov 23 '19 at 23:14
  • yeah i can use milliseconds and subtract, or use `getYear()` `getMonth()` & `getDate()` and subtract but as explained above that can become complicated. JavaScript has a great inherent Date object but the question's scope focuses towards finding an age in year, month & days with that object. i have to imagine others have questioned this before. – sao Nov 23 '19 at 23:19
  • `now.getYear() + 1000`? See [*getFullYear*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getFullYear). – RobG Nov 23 '19 at 23:28
  • @RobG my mistake, it goes from 1900 i believe so i should have wrote +1900. or get full year, thanks for pointing out. – sao Nov 23 '19 at 23:30
  • Due to complication of leap year and time precision stuffs, you should not use milliseconds, use Year difference instead. – Thanh Trung Nov 23 '19 at 23:52

0 Answers0