How to Use PHP Mktime to Create a Countdown

Display the number of days to a specific event on a website

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

Note: Because the ist_dst parameter used in this article 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 site 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 will be until the event occurs.

We can do this 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.

Here's How:

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

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

  2. Establish the current date with this line:
    $today = time () ;
  3. To find the difference between the two date, 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) ;
  1. Put it all together for the final code:
    $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. "How to Use PHP Mktime to Create a Countdown." ThoughtCo, Nov. 21, 2016, Bradley, Angela. (2016, November 21). How to Use PHP Mktime to Create a Countdown. Retrieved from Bradley, Angela. "How to Use PHP Mktime to Create a Countdown." ThoughtCo. (accessed December 15, 2017).