基于js的setTimeout 实现显示服务器时间
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>sdfsa</p>
<div class="footer">
<div class="footer-inner">
<div class="container">
<div class="row">
<div class="span5" id="server-time" style="text-align:right">
</div>
</div>
</div>
</div>
</div>
</body>
<script src="http://***:8000/static/js/jquery-1.7.2.min.js"></script>
<script>
Date.prototype.Format = function (fmt) {
var o = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3),
"S": this.getMilliseconds()
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
$(function () {
initTime = new Date().getTime();
// 此处gettime 接口 返回json 如: {"time": 1649747287965}
$.getJSON("/gettime", function(out) {
// setTime(initTime, out.time);
setTime(initTime, 1649747287965);
});
});
function setTime(initTime,serverTime) {
ellapsedTime = new Date().getTime()-initTime;
$('#server-time').html('当前服务时间: <strong>'+new Date(serverTime+ellapsedTime).Format("yyyy-MM-dd hh:mm:ss")+'</strong>');
setTimeout('setTime('+initTime+','+serverTime+');',500);
}
</script>
</html>
后端 gettime 接口返回当前时间戳带us
{
"time": 1649747287965
}
效果图:
赞赏码
非学,无以致疑;非问,无以广识