我有一个以UTC为时间的JavaScript时钟,它目前有效,但时间基于客户端的计算机。我可以做些什么来改变服务器的时间呢?我使用PHP作为服务器脚本语言。我不想使用AJAX。
<?php
$year = date("Y");
$month = date("m");
$day = date("d");
$hour = date("h");
$minute = date("i");
$str = $year . $month . $day . $hour . $minute;
echo "history.pushState('', 'title', '?q=$str');";
echo "var ct = '$str';";
?>
function dT(){
var d = new Date();
d = new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds());
d.setTime(d.getTime());
v = d.getFullYear() + "" +
padstr(d.getMonth()) + "" +
padstr(d.getDate()) + "" +
padstr(d.getHours()) + "" +
padstr(d.getMinutes()) + "" + padstr(d.getSeconds());
if(ct !== v){
history.pushState('', 'title', '?q=' + v);
ct = v;
}
setTimeout('dT()', 1000);
}
dT();
修改
var a = moment().format("<?php echo date("Y-m-d H:i:s", time()); ?>");
document.getElementById("time").innerHTML = a;
function clock_tick(){
var time = moment(a);
time.add('second', 1);
a = time.format("YYYY-MM-DD HH:MM:SS");
document.getElementById("time").innerHTML = a;
setTimeout("clock_tick()", 1000);
}
clock_tick();
答案 0 :(得分:1)
这应该让你开始。你不需要使用moment.js,但我想尝试一下,因为有人建议它。
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="moment.js"></script>
<script language="javascript">
$(function() {
$('#clock')[0].innerHTML = moment().format("<?php echo date("Y-m-d H:i:s", time()); ?>");
clock_tick();
});
function clock_tick(){
var clock_div = $('#clock')[0];
var time = moment(clock_div.innerHTML);
time.add('second', 1);
clock_div.innerHTML = time.format("YYYY-MM-DD hh:mm:ss");
setTimeout("clock_tick()", 1000);
}
</script>
</head>
<body>
<div id="clock"></div>
</body>
</html>
然后正如我之前所说,你可能需要设置:
date_default_timezone_set("UTC");
答案 1 :(得分:0)