方法一
非常的简单暴力,html格式,复制即用:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p id="time"></p>
<script>
var weekday=new Array(7)
weekday[0]="星期日 "
weekday[1]="星期一 "
weekday[2]="星期二 "
weekday[3]="星期三 "
weekday[4]="星期四 "
weekday[5]="星期五 "
weekday[6]="星期六 "
/*document.write("今天是" + weekday[d.getDay()])*/
function addZero(i){
if (i<10) {
i="0" + i;
}
return i;
}
setInterval(function() {
ajax()
function ajax(option) {
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new window.XMLHttpRequest();
} else { // ie
xhr = new ActiveObject("Microsoft")
}
// 通过get的方式请求当前文件
xhr.open("get", "/");
xhr.send(null);
// 监听请求状态变化
xhr.onreadystatechange = function() {
var time = null, curDate = null;
if (xhr.readyState === 2) {
// 获取响应头里的时间戳
time = xhr.getResponseHeader("Date");
console.log(xhr.getAllResponseHeaders())
curDate = new Date(time);
document.getElementById("time").innerHTML = curDate.getFullYear() + "年"
+ (curDate.getMonth() + 1) + "月"
+ curDate.getDate() + "日 "
+ weekday[curDate.getDay()]
+ addZero(curDate.getHours()) + ":"
+ addZero(curDate.getMinutes()) + ":"
+ addZero(curDate.getSeconds());
}
}
}
}, 1000);
</script>
</body>
</html>
这是电脑的时间2018年2月12日:
手机的时间我设置的是2018年2月15日,测试的显示结果证明是和tomcat服务器的时间一致:
能力有限,秒会偶尔有卡顿的感觉,不影响准确度。
方法二
这个需要引入jQuery
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="../js/jquery-1.10.2.min.js"></script>
</head>
<body>
<script>
$.ajax({type:"OPTIONS",url:"/",complete:function(x){alert(x.getResponseHeader("Date"))}})
</script>
</body>
</html>
在chrome 中看到的是格林威治时间,比北京时间晚8个小时,要+8。