Javascript日期函数设置和获取

Javascript Date Function Setting and getting

本文关键字:获取 设置 函数 日期 Javascript      更新时间:2023-09-26

嗨,我正试图将当天设置为第二天,并用javascript检索。我试过d.getDay(d.setDay(2))以及其他东西。

<script>
    var d = new Date();
    document.write("<br /><span style = '"color: " + 
                   getRandomColor() +"'">My Birthdate is: " 
                   + monthNames[d.getMonth(d.setMonth(0))] + 
                   d.getDay(d.setDay(1)) + "</span>");
</script>

谢谢你的帮助。

根据JavaScript Date Methods,没有setDay方法,getDay返回工作日编号(0-6)而不是日期编号(1-31)。获取日期编号的正确方法是getDate,设置日期编号的错误方法是setDate。你需要更改这个

d.getDay(d.setDay(1))

到这个

d.getDate(d.setDate(2))

所以你的代码应该如下

<script>
    var d = new Date();
    document.write("<br /><span style = '"color: " + 
                   getRandomColor() +"'">My Birthdate is: " 
                   + monthNames[d.getMonth(d.setMonth(0))] + 
                   d.getDate(d.setDate(2)) + "</span>");
</script>