繁体   English   中英

如何使用JavaScript在HTML中显示前一天和第二天的日期

[英]How to display previous day and next day dates in html using Javascript

我正在使用一些简单的JavaScript来显示当前日期以及上一个和下一个日期链接。

我的代码段如下

<script type="text/javascript">
var currentTime = new Date();

var month = currentTime.getMonth()+1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var date = month + " " + day + " " + year;

function ShowSchedule() 
{
document.getElementById("today").innerHTML = date;
}

function ShowDay(isNextDay)
{
if(isNextDay)
{
var nextDay = new Date(year, month, day+1);
date = nextDay.getMonth() + " " + nextDay.getDate() + " " + nextDay.getFullYear();
ShowSchedule();
}
else{
var prevDay = new Date(year, month, day -1);
date= prevDay.getMonth() + " " + prevDay.getDate() + " " + prevDay.getFullYear();
ShowSchedule();
}
}

</script>
</head>
<body>
<table border="1">
    <tr>
        <th>
            <a id = "prev" href="#" onClick="ShowDay(false)">Prev</a>
        </th>
        <th id="today">
        </th>
        <th>
            <a id = "next" href="#" onClick="ShowDay(true)">Next</a>
        </th>
    </tr>
</table>
<script>ShowSchedule();</script>
</body>
</html>

上面的代码也适用于当前日期,上一个日期和下一个日期,但是问题是如果我单击第二天的链接,它只会增加一天,上一个链接也是如此。 我的要求是,我可以通过单击上一个和下一个链接导航到我想要的任何日期。

任何帮助将不胜感激。

new Date((new Date).valueOf() + 86350989) //That will always give you tomorrow (jump ahead 24 hours)

new Date((new Date).valueOf() - 86350989) //Will give you yesterday.

这是正在发生的事情:

new Date(number) //You're specifying a DateTime object using the milliseconds from unix epoch (January 1, 1970)

(new Date).valueOf() //You're getting the milliseconds from unix epoch.

86350989 //Is the number of milliseconds in a day.

最简单的解决方案是:

var d = new Date(); // today
d.setDate(d.getDate() - 1); // yesterday:
d.setDate(d.getDate() + 1); // tomorrow:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM