[英]how to get real server time rather than local pc time for my javascript clock?
function setTime(){
const now=new Date();
// second hand
const seconds=now.getSeconds();
const secondDegree=((seconds/60)*360+90);
const secondhand=document.querySelector('.sec-hand');
secondhand.style.transform=`rotate(${secondDegree}deg)`;
// minute hand
const minhand=document.querySelector('.min-hand');
const mins=now.getMinutes();
const minDegree=((mins/60)*360+90);
minhand.style.transform=`rotate(${minDegree}deg)`;
// hour hand
const hourhand=document.querySelector('.hour-hand');
const hour=now.getHours();
const hourDegree=((hour/12)*360+90);
hourhand.style.transform=`rotate(${hourDegree}deg)`;
}
setInterval(setTime,1000);
据我所知,javascript 无法达到服务器时间。 以前去过那里一次,并通过 xml 请求调用本地 php 文件来修复它,该文件读取当前服务器时间。
可选的,您还可以将时区更改为所需的值。
PHP 文件
<?php
echo time();
JS文件
var now;
function getDate(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
console.log(xmlhttp.responseText);
now = new Date(xmlhttp.responseText*1000);
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", "time.php", true);
xmlhttp.send();
}
function setTime(){
// second hand
const seconds=now.getSeconds();
const secondDegree=((seconds/60)*360+90);
const secondhand=document.querySelector('.sec-hand');
secondhand.style.transform=`rotate(${secondDegree}deg)`;
// minute hand
const minhand=document.querySelector('.min-hand');
const mins=now.getMinutes();
const minDegree=((mins/60)*360+90);
minhand.style.transform=`rotate(${minDegree}deg)`;
// hour hand
const hourhand=document.querySelector('.hour-hand');
const hour=now.getHours();
const hourDegree=((hour/12)*360+90);
hourhand.style.transform=`rotate(${hourDegree}deg)`;
}
getDate();
setInterval(setTime,1000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.