如何使 PHP 日期和时间自动更新
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10160810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make PHP date and time update automatically
提问by jameswildi
I have a script which displays the date and time.
我有一个显示日期和时间的脚本。
How can I add something to make it update automatically instead of on page refresh.
如何添加一些内容以使其自动更新而不是在页面刷新时更新。
Here is the script:
这是脚本:
<?php
$hourdiff = 0; // Replace the 0 with your timezone difference (;
$site = date("l, d F Y g:i a",time() + ($hourdiff * 3600));
echo $site;
?>
Can anyone help. Thanks.
任何人都可以帮忙。谢谢。
回答by Starx
PHP is a server side language, and only ways you are going to send request to the server, are through redirection, navigation, refresh or through an ajax request.
PHP 是一种服务器端语言,您将请求发送到服务器的唯一方式是通过重定向、导航、刷新或通过 ajax 请求。
So, You will need Javascript for that.
因此,您将需要 Javascript。
Here is a simple demo
这是一个简单的演示
setInterval(function() {
var currentTime = new Date ( );
var currentHours = currentTime.getHours ( );
var currentMinutes = currentTime.getMinutes ( );
var currentSeconds = currentTime.getSeconds ( );
currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;
var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";
currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;
currentHours = ( currentHours == 0 ) ? 12 : currentHours;
var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;
document.getElementById("timer").innerHTML = currentTimeString;
}, 1000);
回答by svlada
You can display current time using javascript.
您可以使用 javascript 显示当前时间。
Here is one introducary article about this: http://www.elated.com/articles/creating-a-javascript-clock/
这是一篇关于此的介绍性文章:http: //www.elated.com/articles/creating-a-javascript-clock/
Also posible duplicate: show server time using php and jquery ajax

