我试图从日期字符串中获取月份,只要该日不是该月的第一天(01),这就可以正常工作.如果该日是第一天,则返回上个月:
<!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>
Run Code Online (Sandbox Code Playgroud)
返回:11应该返回:12
如果日期字符串是2013-8-01,那么将返回7,当它应该是8.在"getMonth()"之后没有"+1",那么将返回6而不是7.