Javascript date returns wrong month if day 01

I am trying to get a month from a date string, this works fine until the day is the first month (01). If the day is first, it returns the previous month:

<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the month.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
function myFunction() {
    var str="2014-12-01"
    var d = new Date(str); 
    var m = d.getMonth()+1;
    document.getElementById("demo").innerHTML = m;
}
</script>

</body>
</html>

Refund: 11 Must Return: 12

If the date string was 2013-8-01, then 7 will be returned, when it should be 8. Without "+1" after "getMonth ()" then 6, not 7 will be returned.

+4
source share
3 answers

The actual problem is the time zone of your computer.

Suppose your computer is in Eastern Time (GMT-5):

var foo = new Date('2014-12-01');

foo.toUTCString(); // "Mon, 01 Dec 2014 00:00:00 GMT"
foo.toISOString(); // "2014-12-01T00:00:00.000Z"
foo.toString(); // "Sun Nov 30 2014 19:00:00 GMT-0500 (Eastern Standard Time)"

, , , 10. JavaScript UTC, .

getMonth() , ( .

Date 30 19:00 (7 ), getMonth() 10:

foo.getMonth(); // 10
foo.getUTCMonth(); // 11

, , getUTC*.

Date. , .

+5

JavaScript , . 01 0, . 32 31 . .

0

getMonth () returns a value from 0 to 11: http://www.w3schools.com/jsref/jsref_getmonth.asp January is 0, February is 1, etc.

So, to get the β€œright” month, you have to do +1.

0
source

All Articles