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);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!