-->

Javascript date returns wrong Month if day is 01

2020-04-08 07:33发布

问题:

I am trying to get the Month from the date string, this works fine as long as the day isn't the first of the month (01). If the day is the 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>

Returns: 11 Should Return: 12

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

回答1:

The actual problem lies within the timezone of your computer.

Suppose that 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)"

Notice that the date is actually in November because it's a few hours behind, and therefore the zero-indexed month would be 10. JavaScript automatically assumes UTC when you do not provide a time string.

The getMonth() method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year.

In local time, this Date object represents November 30 at 19h00 (7pm), so getMonth() returns 10:

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

If you are not concerned about time zones and are just dealing with dates, perhaps look into using the getUTC* methods.

You can read more about the Date object here. Hope this helps.



回答2:

JavaScript is doing what it should do. In the day value it interprets the 01 as 0, and a zero value for the day is interpreted as the last day of the previous month. It's like asking for day 32 in a month with 31 days. That would return a date of the first of the next month.



回答3:

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

So to get the 'right' month, you should do +1.