JavaScript setDate()意外行为错误月份 [英] Javascript setDate() unexpected behaviour wrong month

查看:84
本文介绍了JavaScript setDate()意外行为错误月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能向我解释为什么在 defaultDate.setDate(d.getDate());中错误地设置了月份。在下面的代码中?我知道JS从0索引开始运行了几个月,但是我会假设setDate()可以处理所有差异。

Can anyone explain to me why the month is set incorrectly in "defaultDate.setDate(d.getDate());" in the code below? I know that JS runs months from a 0 index, however I would have assumed that setDate() would take care of any discrepencies.

<script>
var defaultDate = new Date();
 window.alert(defaultDate);

function testfunction(){
    var d=new Date();
    window.alert(d);
    d.setDate(d.getDate()-10);
    window.alert(d);
    defaultDate.setDate(d.getDate());
    window.alert(defaultDate);
    }
   testfunction();
</script>


推荐答案

setDate() getDate()函数仅指月中的某天。当您从 d 对象中减去10天时,它也会自动设置月份,因此为 7月。但是,当您设置 defaultDate 对象的日期时,您只需要设置日期(因此,一周中的月份和日期不变)。

setDate() and getDate() functions only refer to the day of the month. When you subtract 10 days from the d object it automatically sets the month too, so as July. But, when you set the date of defaultDate object, you only set the days(so the Month and day of week is not changed).

这篇关于JavaScript setDate()意外行为错误月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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