js 获取服务端时间,并实现时钟
本例子以vue语法伪代码书写:
1,获取服务端北京时间
getRealTime() { let that = this; var xhr = new XMLHttpRequest(); if( !xhr ){ xhr = new ActiveXObject("Microsoft.XMLHTTP"); } xhr.open("HEAD",location.href,true); xhr.onreadystatechange=function(){ if( xhr.readyState == 4 && xhr.status == 200 ){ that.nowTime = xhr.getResponseHeader("Date"); that.changeTime(); } } xhr.send(null); }
2,实现闹钟走动
changeTime() { let that = this; if(that.nowTime){ setInterval(() => { var t = new Date(that.nowTime).getTime(); t += 1000; that.nowTime = new Date(t).pattern('yyyy-MM-dd HH:mm:ss'); }, 1000); } }
3,页面使用
<div>北京时间:{{nowTime}}</div>