JavaScript日期错误2014年2月 [英] JavaScript Date Bug February 2014

查看:84
本文介绍了JavaScript日期错误2014年2月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个JS代码:

So I have this JS-code:

var d1 = new Date();
d1.setFullYear(2014);
d1.setMonth(1);
d1.setDate(1);

应该是2014年2月1日,对吧?只是没有...它返回2014年3月1日(实际上,完整值为 2014年3月1日星期六,格林尼治标准时间+0100(浪漫标准时间))。我勒个去?其他任何日期值也会发生相同的情况。

Should be Feb-01-2014, right? Only it's not... It returns Mar-01-2014 (actually, the full value is "Sat Mar 01 2014 20:54:29 GMT+0100 (Romance Standard Time)"). What the hell? Same thing happens with any other date value.

但是,如果我使用此代码,则可以正常工作:

If I use this code, however, it works fine:

var d1 = new Date(2014,1,1,0,0,0,0);

结果是:Sat Feb 01 2014 00 :00:00 GMT + 0100(浪漫标准时间)

The result is: Sat Feb 01 2014 00:00:00 GMT+0100 (Romance Standard Time)

有什么想法吗?

推荐答案

这是正在发生的事情,一行一行:

Here's what's happening, line for line:

您用今天的日期创建了一个新的日期对象。

You create a new date object with today's date.

var d1 = new Date(); // d1 = 2014-04-30

然后将年份设置为2014 ,所以什么也没有发生。

Then you set the year to 2014, which it already is, so nothing really happens.

d1.setFullYear(2014); // d1 = 2014-04-30

这是棘手的部分,因为现在您将月份更改为二月。但这会使日期2月30日( 2014-02-30 )不存在,因此JavaScript会尝试查找最接近的有效日期,即第一个三月( 2014-03-01 )。

Here's the tricky part, because now you change the month to February. But this would make the date February the 30th (2014-02-30) which doesn't exist, so the JavaScript will try to find the closest valid date which is first of March (2014-03-01).

d1.setMonth(1); // d1 = 2014-02-30 is not valid so JS makes it 2014-03-01

然后将日期设置为本月的第一天,所以这里也没有任何实际发生。

Then you set the day to the first day of the month, which it already is, so nothing really happens here either.

d1.setDate(1) // d1 = 2014-03-01

这篇关于JavaScript日期错误2014年2月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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