在页面上动态显示实时时间

需求:把当前的时间在页面上动态的显示出来


<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>网页动态时间title>
	<script>
		window.onload = function(){
			var span = document.getElementsByTagName('span')[0];
			var dateStr = formatDate();
			// 将时间放置到span内
			span.innerText = dateStr;
			// 每隔一秒,再放置一次最新的时间
			setInterval(function(){
				span.innerText = formatDate();
			},1000);
			//格式化年月日时分秒 
			function formatDate(){
				var date = new Date();
				var year = date.getFullYear();
				var month = date.getMonth()+1;
				month = month<10?'0'+month:month;
				var day = date.getDate();
				day = day<10?'0'+day:day;
				var hours = date.getHours();
				hours = hours<10?'0'+hours:hours;
				var minutes = date.getMinutes();
				minutes = minutes<10?'0'+minutes:minutes;
				var seconds = date.getSeconds();
				seconds = seconds<10?'0'+seconds:seconds;
				// 2019-07-23 09:40:30
				return year+'-'+month+'-'+day+' '+hours+':'+minutes+':'+seconds;
			}

		}
	script>
head>
<body>
	<div>
		当前时间:
		<span>将来放置时间span>
	div>
body>
html>

界面效果:
在页面上动态显示实时时间_第1张图片

你可能感兴趣的:(BOM)