1、通過JavaScript獲取本機的時間,自動更新 <script> function displayTime() { var date = new Date(); //日期對象 var now = ""; now = date.getFullYear() + "年"; now = now + ( ...
1、通過JavaScript獲取本機的時間,自動更新
<script>
function displayTime() {
var date = new Date(); //日期對象
var now = "";
now = date.getFullYear() + "年";
now = now + (date.getMonth() + 1) + "月";
now = now + date.getDate() + "日";
now = now + date.getHours() + "時";
now = now + date.getMinutes() + "分";
now = now + date.getSeconds() + "秒";
document.getElementById("getToday").innerHTML = now;
setTimeout("displayTime()", 1000);
}
window.onload = displayTime;
</script>
<div id="getToday">
</div>
實用小技巧:通過JavaScript可以自動更新顯示在網頁底部版權處的年份
<script type="text/javascript">
copyright=new Date();//取得當前的日期
update=copyright.getFullYear();//取得當前的年份
document.write("Copyright © 2015-"+ update + " All rights reserved.");
</script>
2、通過AJAX獲取服務端的時間,在頁面上自動更新
<script type="text/javascript" src="Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(function () {
setInterval(function () {
$.get("GetTime.aspx?timestamp="+new Date().getTime(),function (data) {
$("#time").html(data);
});
}, 1000);
})
</script>
<div id="time">
</div>
GetTime.aspx後臺代碼:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Response.Write(DateTime.Now.ToString());
}
}
如果僅僅顯示時間,用第1種方法,即通過JavaScript獲取本機的時間,自動更新。