当前位置 : 主页 > 网络编程 > JavaScript >

Date()对象的应用实例

来源:互联网 收集:自由互联 发布时间:2021-07-03
1. [代码] [HTML]代码 !DOCTYPE htmlhtml lang="en"headmeta charset="UTF-8"title时间显示效果/titlescript type="text/javascript" window.onload = function(){ showTime(); freshTime(); } function checkTime(i){ //补位处理 if(i10){ i="

1. [代码][HTML]代码    

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>时间显示效果</title>
	<script type="text/javascript">
  window.onload = function(){
    showTime();
    freshTime();
  }

  function checkTime(i){  //补位处理
      if(i<10){
          i="0"+i;
      }
    return i;
  }
//时间显示效果
  function showTime(){
    var now=new Date();
    var year=now.getFullYear();
    var month=now.getMonth()+1;//从0开始计时
    var day=now.getDate();
    var d=now.getDay();//从0开始计
    var h=now.getHours();
    var m=now.getMinutes();
    var s=now.getSeconds();
    m=checkTime(m);
    s=checkTime(s);

    var weekday=new Array(7);
    weekday[0]="星期日"
    weekday[1]="星期一"
    weekday[2]="星期二"
    weekday[3]="星期三"
    weekday[4]="星期四"
    weekday[5]="星期五"
    weekday[6]="星期六"

    document.getElementById("time").innerHTML=""+year+"年"+month+"月"+day+"日 "+  weekday[d] +h+":"+m+":"+s;
    t=setTimeout('showTime()',500);//半秒运行一次
  }
  //倒计时效果
  function freshTime(){
    var endtime = new Date("2016,6,6,12:00:00");
    var nowtime = new Date();
    var lefttime = Math.floor((endtime.getTime() - nowtime.getTime())/1000);//获取总秒数
    var d = Math.floor(lefttime/(24*60*60));//获取天数
    var h = Math.floor(lefttime/(60*60)%24);//获取时数
    var m = Math.floor(lefttime/(60)%60);//获取分数
    var s = Math.floor(lefttime%60);//获取秒数
    m=checkTime(m);
    s=checkTime(s);

    if(lefttime<=0){
      document.getElementById("counter").innerHTML="计时结束";
      clearTimeout(sh);
    }else{
       document.getElementById("counter").innerHTML="距离结束还有 "+d+"天"+h+"时"+m+"分"+s+"秒";
    }
    sh = setTimeout("freshTime()",500);
  }
	</script>
</head>
<body>
	<p>显示系统时间:<span id="time"></span></p>
	<p>显示倒计时:<span id="counter"></span></p>
</body>
</html>
网友评论