2021-06-04

如何用JavaScript写出一个计时器


<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		
		<script type="text/javascript">
/**
			 *  常用方法
			 */
			var today=new Date(); 
			var year=today.getFullYear();
			var month=today.getMonth()+1;
			var date=today.getDate();
			var hour=today.getHours();
			var minute=today.getMinutes();
			var second=today.getSeconds();
			var milliSecond=today.getMilliseconds();
			var day=today.getDay();
			var weekday=['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];
			var time=today.getTime(); // 返回从1970-01-01 00:00:00至今的毫秒数
			
			console.log(year+'年'+month+'月'+date+'日 '+hour+':'+minute+':'+second+' '+milliSecond+' '+weekday[day]); 
            function showTime(){
				
			var today=new Date();
			var duoHand=new Date(2021,5,18);//时间
			var seconds=Math.floor((duoHand.getTime()-today.getTime())/1000);
			if(seconds<=0){
				document.getElementById('time').innerHTML='可以开始剁手了!';
				return;
			}
			
			var day=Math.floor(seconds/60/60/24);
			var hour=checkNum(Math.floor(seconds/60/60%24));
			var minute=checkNum(Math.floor(seconds/60%60));
			var second=checkNum(seconds%60);

			
			var time='距离6·18还有:'+day+'天 '+hour+'小时'+minute+'分'+second+'秒';//判断时间
			
			document.getElementById('time').innerHTML=time;
			
			setTimeout(showTime,1000);
			}
			
			
			function checkNum(num){
				if(num<10){
					return '0'+num;
				}
				return num;
			}
			
			window.onload=function(){
				showTime();
			}
		
			
		</script>
		
	</head>
	<body>
		<div id="time"></div>
	</body>
</html>

 

上一篇:计算多少天后的日期


下一篇:Linux文本检索命令grep笔记