Unable to get the correct Month for Date

Viewed 33

I have a minor issue. I am not sure what I am doing wrong, but the getMonth() method is getting the 7th month even though it is the 8th month of the year.

I am not sure why that is, am I missing a step?

function startTime() {
  const today = new Date();

  let hour = today.getHours();
  let minutes = today.getMinutes();
  let seconds = today.getSeconds();


  let day = today.getDate();
  let month = today.getMonth();
  let year = today.getFullYear();

  minutes = checkTime(minutes);
  seconds = checkTime(seconds);

  document.querySelector('.dateTime').innerHTML = hour + ":" + minutes + ":" + seconds;
  document.querySelector('.day').innerHTML = day + "/" + month + "/" + year;
  setTimeout(startTime, 1000);
}

setTimeout(startTime, 1000);

function checkTime(i) {
  if (i < 10) {
    i = "0" + i
  }; // add zero in front of numbers < 10
  return i;
}
<div class="time-display">
  <div class="dateTime"></div>
  <div class="day"></div>
</div>

1 Answers

The .getMonth() method return the zero-indexed month (ie: January is 0, February is 1, etc). All you need to do is add one to the result. Like this:

// ... code ...

  let day = today.getDate();
  let month = today.getMonth()+1;
  let year = today.getFullYear();

// ... more code ...
Related