明天的动态javaScript日期指向日期

时间:2014-11-03 12:42:09

标签: javascript

我使用以下脚本创建动态日期。

HTML:

<span id="spanDate"></span>

剧本:

var months = ['01','02','03','04','05','06','07',
        '08','09','10','11','12'];       
        var tomorrow = new Date(Date.now() + (1000*3600*24));
        //tomorrow.setTime(tomorrow.getTime() + (1000*3600*24));       
        document.getElementById("spanDate").innerHTML = ('00' + tomorrow.getDate()).slice(-2) + "/" + months[tomorrow.getMonth()] + "/" + tomorrow.getFullYear();

Fiddle Link

当我渲染此代码时,它会在我的机器日期显示第二天(即明天)的日期,并且不显示今天的日期。为什么会这样?

2 个答案:

答案 0 :(得分:2)

因为您在初始化日期时添加了一天吗?

 //You add 1000*3600*24 milliseconds: 1 day ===> outcome is tomorrow
 tomorrow.setTime(tomorrow.getTime() + (1000*3600*24)); 

尝试

var tomorrow = new Date(Date.now());

小提琴:http://jsfiddle.net/n4e87x6k/3/

也许从&#34;明天&#34;更改您的参数也很有用。今天&#34;今天&#34; ; - )

答案 1 :(得分:1)

这是因为您在Date构造函数中将当前时间添加了一整天。如果要显示当前日期使用

var today = new Date();

并替换

document.getElementById("spanDate").innerHTML = ('00' + tomorrow.getDate()).slice(-2) + "/" + months[tomorrow.getMonth()] + "/" + tomorrow.getFullYear();

document.getElementById("spanDate").innerHTML = ('00' + today.getDate()).slice(-2) + "/" + months[today.getMonth()] + "/" + today.getFullYear();