Javascript日期返回错误月份,如果日期为01 [英] Javascript date returns wrong Month if day is 01

查看:134
本文介绍了Javascript日期返回错误月份,如果日期为01的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从日期字符串中获取月份,只要这一天不是本月的第一个(01),这个工作正常。如果一天是第一个,那么它返回上个月:

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>

退货:11
应退货:12

Returns: 11 Should Return: 12

如果日期字符串是2013-8-01,那么7将被返回,当它应该是8.没有在getMonth()之后的+1时,将返回6,而不是7。

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.

推荐答案

实际问题在于计算机的时区。

The actual problem lies within the timezone of your computer.

假设您的计算机位于东部时间(GMT-5):

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

请注意,日期实际上是在11月,因为它几个小时后,因此零索引月份将是10.当您没有提供时间字符串时,JavaScript将自动采用UTC。

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.


getMonth() 方法根据当地时间返回指定日期的月份,作为零基值(其中0表示年度的第一个月份

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.

在当地时间,此Date对象表示11月30日19时00分(晚上7点),所以 getMonth() 返回10:

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

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

如果你不关心时区,只是处理日期,也许看看使用 getUTC * 方法。

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

您可以在这里阅读有关 Date 对象的更多信息希望这有帮助。

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

这篇关于Javascript日期返回错误月份,如果日期为01的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆