1

I have a problem, I want the difference between 2 dates and I do not have the same result:

let start = moment('2022-11-01 00:00:00').tz('Europe/Paris');
start = start.subtract(6, 'months');

const end = moment('2022-11-01 00:00:00').tz('Europe/Paris');

console.log(end.format('LLL')); // 1 novembre 2022 00:00
console.log(start.format('LLL')); // 1 mai 2022 00:00
const duration = moment.duration(end.diff(start));
console.log("years", duration.years());
console.log("months", duration.months());
console.log("days", duration.days());
console.log("hours", duration.hours());
console.log("minutes", duration.minutes());
console.log("seconds", duration.seconds());
console.log("milliseconds", duration.milliseconds());
/*
{
  years: 0,
  months: 6,
  days: 1,
  hours: 1,
  minutes: 0,
  seconds: 0,
  milliseconds: 0,
}
*/
.as-console-wrapper {
    max-height: 100% !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.39/moment-timezone-with-data-10-year-range.min.js"></script>

As you can see, I subtract 6 months with the subtract function, but when I check the difference between the 2 dates with diff, it tells me that there are 6 months 1 day and 1 hour.

For the "1 hour", I found it. It's because of the time change in France which happened on October 30, 2022, but for the "1 day" I don't have an explanation.

My version of moment is 2.29.4, moment-timezone is 0.5.35.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
w-jerome
  • 11
  • 1
  • I guess the end day is included, i would do : `end.subtract(1, 'day').diff(start)` – Lk77 Nov 16 '22 at 13:23
  • I would use GMT timezone instead to do a precise diff between two dates: https://runkit.com/lk77/6374e6a6ba9b07000885c270 – Lk77 Nov 16 '22 at 13:31
  • So I thought about it, but the variable `.subtract(6, 'months')` is a parameter that can change. And I can also do `.subtract(6, 'years')`, except in this case I don't have a problem, so the `subtract(1, 'day')` rule shouldn't be present. – w-jerome Nov 16 '22 at 16:41

0 Answers0