2012-05-07 66 views
1

我正在使用一些簡單的Javascript來顯示當前日期以及上一個日期和下一個日期鏈接。如何使用Javascript在html中顯示前一天和下一天的日期

我的代碼片段如下

<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> 

上面的代碼當前,過去和未來日期也在努力,但problam是,如果我點擊第二天鏈接它會得到提高只有一天,同以前的鏈接的東西也。我的要求是我可以通過點擊上一個和下一個鏈接導航到任何我想要的日期。

任何幫助將不勝感激。

回答

1
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. 
+0

Mushin您好,感謝您的回覆,使用此還我能夠nvaigate只有前一天和一個第二天的日期,但不超過一天。任何建議plz。 – Nithin

+0

如果這回答了您的問題,將帖子標記爲答案是很好的禮儀。靠近上/下箭頭。謝謝 – MushinNoShin

+0

謝謝大家,我有解決方案.. – Nithin

相關問題