1

This is how I simply calculate an age, by using a current date and a birthday date:

const now = moment(current)
const bday = moment(birthday)
const diff = now.diff(bday)
const { _data } = moment.duration(diff)
console.log(_data);

I set these values, which should be exactly one year diff...

current: 2021-11-20T23:00:00.000Z
birthday: 2020-11-20T23:00:00.000Z

...and which results in these moment dates:

Moment<2021-11-21T00:00:00+01:00>
Moment<2020-11-21T00:00:00+01:00>

Surprisingly I do get this result:

{
    milliseconds: 0,
    seconds: 0,
    minutes: 0,
    hours: 0,
    days: 30,
    months: 11,
    years: 0
}

But I would expect 1 year. Is this a misconception of myself?

diff results in 31536000000.

user3142695
  • 15,844
  • 47
  • 176
  • 332
  • 1
    11 months, 30 days is equivalent to 1 year only if the start date is in a month of 31 days and the previous month has 30 days. Adding 11 months to 21 Nov gives 21 Oct. Adding 30 days gives 20 Nov since Oct has 31 days. To use durations of units greater than weeks, rules are required to deal with such issues. E.g. should adding 1 year to 29 Feb result in 28 Feb or 1 Mar? Both are equally viable to me. See [*Difference between two dates in years, months, days in JavaScript*](https://stackoverflow.com/questions/17732897/difference-between-two-dates-in-years-months-days-in-javascript). – RobG Dec 07 '21 at 11:04

1 Answers1

3

Try this if you want the difference in years:

const current = '2021-11-20T23:00:00.000Z';
const birthday = '2020-11-20T23:00:00.000Z';

const now = moment(current);
const bday = moment(birthday);

const diff = now.diff(bday, 'years');

console.log(diff);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Your way results in:

const current = '2021-11-20T23:00:00.000Z';
const birthday = '2020-11-20T23:00:00.000Z';

const now = moment(current);
const bday = moment(birthday);

const diff = moment.duration(now.diff(bday)).asYears();

console.log(diff);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
  • My problem is, that I need to calculate the age of children. Some of them are only a few months old, others a few years. That's why I thought of using the `{ days, months, years }` solution. And that's why I can't use your idea. – user3142695 Dec 07 '21 at 09:51
  • There a third parameter that you can use to get the difference in years but decimal ``now.diff(bday, 'years', true)``, not sure if this is what you're looking for. – Majed Badawi Dec 07 '21 at 09:56
  • Check this as well: https://stackoverflow.com/questions/33988129/moment-js-get-difference-in-two-birthdays-in-years-months-and-days – Majed Badawi Dec 07 '21 at 09:58
  • @user3142695 - Perhaps use months when the difference is less than a year: `const diff = now.diff(bday, "months");` – T.J. Crowder Dec 07 '21 at 10:00