JavaScript實時變化的時間

admin發表於2018-02-12

在很多網站都有這樣的功能,能夠顯示當前的事件,這樣或許能夠增加美觀度,當然更加能夠提高網頁的人性化程度,能夠讓給使用者實時瞭解當前時間,這樣能夠給網站增色不少。下面分享一段能夠獲取當前時間,並且能夠進行格式化的程式碼:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="author" content="http://www.softwhy.com/" />
<title>javascript實現的時間顯示程式碼-螞蟻部落</title>
<script type="text/javascript"> 
function clockon(bgclock){
  var now = new Date();
  var year = now.getFullYear();
  var month = now.getMonth();
  var date = now.getDate();
  var day = now.getDay();
  var hour = now.getHours();
  var minu = now.getMinutes();
  var sec = now.getSeconds();
  var week;
  month = month+1;
  if(month<10)month="0"+month;
  if(date<10)date="0"+date;
  if(hour<10)hour="0"+hour;
  if(minu<10)minu="0"+minu;
  if(sec<10)sec="0"+sec;
  var arr_week = new Array("星期日","星期一","星期二","星期三","星期四","星期五","星期六");
  week = arr_week[day];
  var time = "";
  time = year+"年"+month+"月"+date+"日"+week+""+hour+":"+minu+":"+sec;
  bgclock.innerHTML="["+time+"]";
  var timer = setTimeout("clockon(bgclock)",200);   
}
window.onload=function(){
  var bgclock=document.getElementById("bgclock");
  clockon(bgclock);
}
</script>
</head>
<body>
<div id="bgclock"></div>
</body>
</body>
</html>

相關文章