Arrow

Date countdown code in php Share on Facebook

This was the first php script that I ever looked up sooooo many years ago. It’s really quite simple. You want to show visitors a countdown in days to a certain event in the future. Since PHP can provide the current time on the server to the very second, simply calculate the desired date (in seconds) and subtract from the server date. More complicated scripts can give a choice between hours, months, or days remaining, can compensate for a server time different than your current time, and can probably dress up the output a bit better.

I’ve spiced this code up a bit by making it a function (thus enhancing reusability), but otherwise, let’s go with simple, shall we?

Here’s the code:

<?
function countdown($event,$month,$day,$year) {
// subtract desired date from current date and give an answer in terms of days
$remain = ceil((mktime(0,0,0,$month,$day,$year) - time()) / 86400);
// show the number of days left
if ($remain > 0) {
print "<p><strong>$remain</strong> more sleeps until $event</p>";
}
// if the event has arrived, say so!
else {
print "<p>$event has arrived!</p>";
}
}

// call the function
countdown("Christmas Day", 12, 25, 2008);
?>

Here’s the output:

Christmas Day has arrived!

How about some more fun:

Christmas countdown

Update: I have since made a countdown plugin for Wordpress that incorporates the basic concept.

Arrow

5 Responses to “Date countdown code in php”



  1. Julia says:

    Hey pretty cool! This is just what I was thinking I need! How do I use that? Do I just cut and paste that code somewhere?



  2. Philip says:

    Cheers for the code, worked great!



  3. Crystal says:

    I was looking for this exact code. Thank you very much!



  4. Distorzija says:

    This is exactly what I need! Thanks for sharing, mate! Well done.



  5. Mach37 says:

    Hey Cheersfor this code!!! ;) Great blog!
    I will do that into my image how many days remaining to school end :D

Speak your mind

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word