我在服务器时间上挣扎。我的网站上需要计时器(每秒计数),但不是客户端时间,而是服务器。但是我的脚本仅在客户端时间内运行:
<script>
setInterval(function() {
var d = new Date();
$('#timer').text((d.getHours() +':' + d.getMinutes() + ':' + d.getSeconds() ));
}, 1000);
</script>
<label id="timer"></label>
上面的脚本工作正常。如何集成服务器时间并更新一秒钟?
从服务器获取日期,将其转换为javascript日期,然后自己递增。
<?php $today = getdate(); ?>
<script>
var d = new Date(Date.UTC(<?php echo $today['year'].",".$today['mon'].",".$today['mday'].",".$today['hours'].",".$today['minutes'].",".$today['seconds']; ?>));
setInterval(function() {
d.setSeconds(d.getSeconds() + 1);
$('#timer').text((d.getHours() +':' + d.getMinutes() + ':' + d.getSeconds() ));
}, 1000);
</script>
<label id="timer"></label>
编辑:JSFiddle与示例PHP相呼应。
我使用服务器时间编写了倒计时代码。您可以在代码中使用与此类似的内容
<?php
$now = date('d-m-Y');
$end= "01-01-2013"
$date = strtotime($end) - strtotime($now);
$days = date('d', $date);
$monthes= date('m', $date);
$years= date('Y', $date);
?>
<script>
var days = "<?= $days ?>";
var monthes= "<?= $monthes?>";
var years= "<?= $years?>";
document.getElementById('countdown').innerHTML = days+ ' days';
document.getElementById('countdown').innerHTML += monthes+ ' monthes';
document.getElementById('countdown').innerHTML += years+ ' years';
</script>