April 15, 2012
How to make PHP date and time update automatically
Question 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.
Answer 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.
So, You will need Javascript for that.
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);