Home > Enterprise >  Calculation of duration between two dates doesn't result in expected result
Calculation of duration between two dates doesn't result in expected result

Time:12-08

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.

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related