Use PHP Mktime to Create a Countdown

Executive working on his laptop
GlobalStock/E+/Getty Images

Because the ist_dst parameter used in this example was deprecated in PHP 5.1 and removed in PHP 7, it is not safe to rely on this code to deliver accurate results in current versions of PHP. Instead, use the date.timezone setting or the date_default_timezone_set() function.

If your webpage focuses on a specific event in the future such as Christmas or your wedding, you may want to have a countdown timer to let users know how long it is until the event occurs. You can do this in PHP using timestamps and the mktime function.

The mktime() function is used to artificially generate the timestamp for a selected date and time. It works the same as the time() function, except it is for a specified date and not necessarily today's date.

How to Code the Countdown Timer

  1. Set a target date. For example, use February 10th, 2017. Do that with this line, which follows the syntax : mktime(hour,minute,second,month,day,year: ist _dst).
    $target = mktime(0, 0, 0, 2, 10, 2017) ;
  2. Establish the current date with this line:
    $today = time () ;
  3. To find the difference between the two dates, simply subtract:
    $difference =($target-$today) ;
  4. Since the timestamp is measured in seconds, convert the results into whatever units you want. For hours, divide by 3600. This example uses days so divide by 86,400—the number of seconds in a day. To make sure the number is an integer, use the tag int.
    $days =(int) ($difference/86400) ;
  5. Put it all together for the final code:
    <?php $target = mktime(0, 0, 0, 2, 10, 2017) ; $today = time () ; $difference =($target-$today) ; $days =(int) ($difference/86400) ; print "Our event will occur in $days days"; ?> 
mla apa chicago
Your Citation
Bradley, Angela. "Use PHP Mktime to Create a Countdown." ThoughtCo, Feb. 16, 2021, Bradley, Angela. (2021, February 16). Use PHP Mktime to Create a Countdown. Retrieved from Bradley, Angela. "Use PHP Mktime to Create a Countdown." ThoughtCo. (accessed March 21, 2023).