1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

How To use mktime to create a countdown


Executive working on his laptop
GlobalStock/E+/Getty Images
If your site focuses on a specific event such as Christmas or your wedding, you may want to have a count down to let users know how long it will be until the event occurs. We can do this using timestamps and the mktime function.
Difficulty: Easy
Time Required: 5 minutes

Here's How:

  1. First we need to set our target date. For our example we will use February 10th, 2007. We would get that with this line:

    $target =  mktime(0, 0, 0, 2, 10, 2007) ;

    More information on phrasing the mktime function can be found in the PHP Functions section.

  2. Next we need to get the current date. We can do that with this line:

    $today = time () ;

    More information on the time function.

  3. We now have to find the difference between them. To do that we simply need to subtract:

    $difference =($target-$today) ;

  4. Since the timestamp is measured in second, we need to convert this into whatever units we want. If we want hours we can divide by 3600, however in our example we will be using days so we need to divide by 86400 (the number of seconds in a day.) We also want to make sure our number is an integer, so we will use the tag int.

    $days =(int) ($difference/86400) ;

  5. When we put it all together we get our final code:

    $target = mktime(0, 0, 0, 2, 10, 2007) ;
    $today = time () ;
    $difference =($target-$today) ;
    $days =(int) ($difference/86400) ;
    print "Our event will occur in $days days";

  1. About.com
  2. Technology
  3. PHP / MySQL
  4. Learn PHP
  5. Clock Countdown and Timer - PHP mktime

©2014 About.com. All rights reserved.