1
  let date = new Date("2017-09-12T12:00:00");
  console.log(date.getUTCMonth());

Here I am expecting it would log 09 for a month but it's logging 08. Year, day , hour and minute gets parsed correctly though. what's going on here? How can I extract 09 from the above date string?

Prajeet Shrestha
  • 7,978
  • 3
  • 34
  • 63

3 Answers3

3

The getUTCMonth() is a zero-based value — zero is January.

For more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCMonth

Albert Einstein
  • 7,472
  • 8
  • 36
  • 71
Mark
  • 90,562
  • 7
  • 108
  • 148
3

date.getUTCMonth() method returns the month (from 0 to 11) for the specified date.

So to get what you expect, you should add 1.

Albert Einstein
  • 7,472
  • 8
  • 36
  • 71
meisen99
  • 576
  • 4
  • 16
2

Months are 0-indexed in Javascript.

var date = new Date(date),
    month = '' + (date.getMonth() + 1),
    day = '' + date.getDate(),
    year = date.getFullYear();

For a quick example is how you would format it if you wanted to format it in a YYYY - MM - DD format.

Alex Gelinas
  • 147
  • 1
  • 10