js實現的獲取當前日期時間的程式碼例項

螞蟻小編發表於2017-03-16

很多網頁都有這樣的功能,在網頁的某一個地方能夠顯示當前系統的日期時間,這個功能是否能夠對瀏覽者有多少幫助不得而知,因為每一臺電腦都有這樣的功能,不過既然有需要,作為程式設計師的我們就要實現,下面是一段這樣的程式碼例項,希望能夠給程式碼帶來一定的幫助,程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
#timer{
  width:350px;
  height:30px;
  margin:0px auto;
  text-align:center;
}
</style>
<script type="text/javascript">
function Clock() {
  var date = new Date();
  this.year = date.getFullYear();
  this.month = date.getMonth() + 1;
  this.date = date.getDate();
  this.day = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六")[date.getDay()];
  this.hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
  this.minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  this.second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  this.toString=function(){
    return "現在是:"+this.year+"年"+this.month+"月"+this.date+"日 "+this.hour+":"+this.minute+":"+this.second+" "+this.day; 
  };
}
window.onload=function(){
  var timer=document.getElementById("timer");
  timer.innerHTML=new Clock().toString();
}
</script>
</head>
<body>
<div id="timer"></div>
</body> 
</html>

相關文章