akc42
akc42

Reputation: 5001

Does Javascript recognise leap years

I have the following snippet of code (actually I am using new Date() to get today (4th March 2016), but it won't be March for ever, so to be a sensible test I had made the date explicitly.

var n = new Date(2016,2,4);
var d = new Date (
  n.getFullYear(),
  n.getMonth(),
  -1,
   6,0,0);
console.log(d.toString());

when n is now (except it isn't) and d is a new date which I want to be the last day of the preceding month. I am NOT getting 29th February 2016 6:00am UTC, which is what I would have expected, instead I am getting 28th February.

This gives the same result in both Chrome and Iceweasel (Firefox). How should I find the last day of the previous month (especially, like this year when it is a leap year)

If it matters, I am in the GMT timezone.

Upvotes: 1

Views: 72

Answers (2)

Giovanni Perillo
Giovanni Perillo

Reputation: 303

In fact, it recognizes

If you try this, it works: Date (2016, 2, 0);

It brings to me Mon Feb 29 2016 00:00:00 GMT-0300

Instead of -1, try 0:

var n = new Date(2016,2,1);
var d = new Date (
            n.getFullYear(),
            n.getMonth(),
            0,
            6,0,0);
console.log(d.toString());

Upvotes: 1

Mike Cluck
Mike Cluck

Reputation: 32511

That's because days are 1 based, not 0 based.

var march4 = new Date(2016, 2, 4);
var feb29 = new Date(
  march4.getFullYear(),
  march4.getMonth(),
  0); // <-- go to the day before the first of the given month
console.log(feb29); // Mon Feb 29 2016 00:00:00 GMT-0700 (Mountain Standard Time)

For reference, if you pull the same trick for April to March, you'll get March 31st.

var april = new Date(2016, 3, 4);
var march = new Date(
  april.getFullYear(),
  april.getMonth(),
  0);
console.log(march); // Thu Mar 31 2016 06:00:00 GMT-0600 (Mountain Daylight Time)

Upvotes: 4

Related Questions