-2

Javascript is reporting that February has 31 days. The code below shows that the second month has more days than it should. What's going on?

    var currentDate = new Date(2018, 2, 4);

    function getDaysInMonth(month, year) {
      var date = new Date(year, month, 1);
      var days = [];
      while (date.getMonth() === month) {
        days.push(new Date(date));
        date.setDate(date.getDate() + 1);
      }
      return days;
    }

    var dayArr = getDaysInMonth(currentDate.getMonth(), currentDate.getFullYear());
    alert('month: '+currentDate.getMonth()+' year: '+currentDate.getFullYear()+' days: '+dayArr.length);
earl3s
  • 2,393
  • 1
  • 23
  • 24
Adil Heybetov
  • 13
  • 1
  • 7
  • 10
    `Date(2018, 2, 4)` is March 4. In JavaScript months are zero-based – j08691 Dec 20 '17 at 18:05
  • There is no need for a Fiddle. Just include your code in a code snippet right here in your question. – Scott Marcus Dec 20 '17 at 18:06
  • 1
    1 = feb........ – mehulmpt Dec 20 '17 at 18:06
  • 1
    If this is for a production script (not just an exercise), you might want to consider using a JS sate library (such as [Moment.js](https://momentjs.com/)), as they usually handle all the weird and unexpected behaviour for you. – nageeb Dec 20 '17 at 18:08
  • 1
    This is actually a duplicate of [*javascript is creating date wrong month*](https://stackoverflow.com/questions/12254333/javascript-is-creating-date-wrong-month) (or any of the many other duplicates). – RobG Dec 20 '17 at 22:49

1 Answers1

1

That's because months are 0 indexed, so month 2 in JS is March. Try it with,

var currentDate = new Date(2018, 1, 4);

That will output 28 days.

earl3s
  • 2,393
  • 1
  • 23
  • 24