我有php日期:
<?php
date_default_timezone_set('Europe/London');
echo date('D M d Y H:i:s O');
?>
和JavaScript/jquery脚本在网站上发布日期:
setInterval(function() {
var d = new Date("<? echo date('D M d Y H:i:s O'); ?>")
currentHours = d.getHours();
currentHours = ("0" + currentHours).slice(-2);
currentMinutes = d.getMinutes();
currentMinutes = ("0" + currentMinutes).slice(-2);
currentSec = d.getSeconds();
currentSec = ("0" + currentSec).slice(-2);
$('#timer').text((currentHours +':' + currentMinutes + ':' + currentSec ));
},
但是javascript返回aN:aN:aN如何将服务器时间插入javascript?
您可以简单地将new Date()
用作
<script>
function myFunction(obj) {
var today = new Date("<?php echo date('Y-m-d H:i:s')?>");
var hh = today.getHours();
var ii = today.getMinutes();
var ss = today.getSeconds();
if (hh < 10) {
hh = '0' + hh
}
if (ii < 10) {
ii = '0' + ii
}
if (ss < 10) {
ss = '0' + ss
}
obj.value = hh + ':' + ii + ':' + ss;
}
</script>
<input type="text" onclick="myFunction(this);">
按如下方式使用代码:
我刚刚new Date("<? echo date('D M d Y H:i:s O'); ?>")
替换到
new Date("<?php echo date('D M d Y H:i:s O'); ?>")
它为我工作
var d = new Date("<?php echo date('D M d Y H:i:s O'); ?>")
alert(d);
currentHours = d.getHours();
currentHours = ("0" + currentHours).slice(-2);
currentMinutes = d.getMinutes();
currentMinutes = ("0" + currentMinutes).slice(-2);
currentSec = d.getSeconds();
currentSec = ("0" + currentSec).slice(-2);
$('#timer').text((currentHours +':' + currentMinutes + ':' + currentSec ));
你在 php 日期中打错了字,它应该是字符串末尾的 0(零)而不是 O。
setInterval(function() {
var d = new Date("<? echo date('D M d Y H:i:s 0'); ?>")
currentHours = d.getHours();
currentHours = ("0" + currentHours).slice(-2);
currentMinutes = d.getMinutes();
currentMinutes = ("0" + currentMinutes).slice(-2);
currentSec = d.getSeconds();
currentSec = ("0" + currentSec).slice(-2);
$('#timer').text((currentHours +':' + currentMinutes + ':' + currentSec ));
},
另请参阅 https://jsfiddle.net/r3b56h2o/以获取有效的答案。