PHP与JavaScript代码,活时钟 [英] PHP with javascript code, live clock
问题描述
嘿我想创建一个活动时钟把它放在我的网站上。所以我写了一个带有JavaScript代码的简单php,就是这样:
Hey I would to create a live clock to put it on my website. So I wrote a simple php with JavaScript code for that, here is it:
<?php
Function d1() {
$time1 = Time();
$date1 = date("h:i:s A",$time1);
echo $date1;
}
?>
<script type="text/javascript">
window.onload = startInterval;
function startInterval() {
setInterval("startTime();",1000);
}
function startTime() {
document.getElementById('qwe').innerHTML = '<?php d1();?>';
}
</script>
<div id="qwe">test</div>
当运行此代码时输出如2:40:17 PM
, div
每秒刷新一次,但问题是时间永远不会改变。
When run this code the output like "2:40:17 PM"
, the div
refreshed every second but the problem is the time never changed.
推荐答案
从PHP获取您想要开始时钟的初始时间:
Get the initial time you want to start your clock with from PHP:
<script>
var now = new Date(<?php echo time() * 1000 ?>);
function startInterval(){
setInterval('updateTime();', 1000);
}
startInterval();//start it right away
function updateTime(){
var nowMS = now.getTime();
nowMS += 1000;
now.setTime(nowMS);
var clock = document.getElementById('qwe');
if(clock){
clock.innerHTML = now.toTimeString();//adjust to suit
}
}
</script>
为了格式化日期,有很多选项(MDN Date API: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date )
For formatting the date there's a zillion options (MDN Date API: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date)
这篇关于PHP与JavaScript代码,活时钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!