2

When developing an firefox add-on the following gives different results?

var out = document.getElementById('out');

out.textContent += new Date(2015, 1, 6, 16, 0, 0, 0) + '\n'; // -> Date "2015-02-06T15:00:00.000Z" correct, months are zero-based
var dt = new Date(0, 0, 0, 0, 0, 0, 0);
dt.setFullYear(2015);
dt.setMonth(1);
dt.setDate(6);
dt.setHours(16);
out.textContent += dt + '\n'; // -> Date "2015-03-06T15:00:00.000Z" ??
<pre id="out"></pre>

The problem is the setMonth(1) sets March in the second case. This happens to arbitrary dates, other dates work just fine with both approaches. Any idea why?

var out = document.getElementById('out');

out.textContent += new Date(2015, 0, 30, 16, 0, 0, 0) + '\n'; // -> 2015-01-30T15:00:00.000Z" months are zero-based
var dt = new Date(0, 0, 0, 0, 0, 0, 0);
dt.setFullYear(2015);
dt.setMonth(0);
dt.setDate(30);
dt.setHours(16);
out.textContent += dt + '\n'; // -> 2015-01-30T15:00:00.000Z
<pre id="out"></pre>
Xotic750
  • 22,914
  • 8
  • 57
  • 79
BennyHilarious
  • 373
  • 3
  • 15

1 Answers1

4

It's because of wrapping, and has nothing to do with Firefox or Firefox addons.

var dt = new Date(0, 0, 0, 0, 0, 0, 0);
dt.setFullYear(2015);
dt.setMonth(1);
dt.setDate(6);
dt.setHours(16);

Originally, dt is Dec 31 1899.

Now, we set it to 2015: Dec 31 2015

The month becomes February, but because February only has 28 days, it wraps around to March: Mar 03 2015

And then, of course, the date is the sixth, so March 6th.

Scimonster
  • 32,893
  • 9
  • 77
  • 89
  • many thanks! Changed the title not to blame Firefox add-ons :) – BennyHilarious Feb 09 '15 at 07:42
  • @scimonster That is the reason but do you have any general advice to prevent this from happening? – Xotic750 Feb 09 '15 at 08:37
  • @Xotic750 Construct it all at once. – Scimonster Feb 09 '15 at 08:37
  • @scimonster Ok, we know that from the OP's question. I would say `new Date(0)`, setting to the Epoch `midnight 01 January, 1970 UTC`. This issue would then have be avoided (except in cases where the `Date` object is reused without resetting it to the Epoch first `dt.setTime(0)`). – Xotic750 Feb 09 '15 at 08:42
  • I agree the choice ( if it is a choice) to set the dt to 31st Dec 1899 makes it very likely to create such bugs. – BennyHilarious Feb 09 '15 at 08:58