Elisimo
Elisimo

Reputation: 77

How to make "time left until closing" in PHP

I have a website and i want to display something like "2 hours 25 minutes until closing" and when closing hours begin, i want it to say "We are curently closed". I am sort of weak in php, so please any help is appreciated. So technically i want to compare 2 different times of day (opens at 08:00, closes at 16:00).

Upvotes: 1

Views: 448

Answers (1)

urlex
urlex

Reputation: 36

Using the time(), mktime(), and gmdate() functions in PHP you can statically return how many hours and minutes are left before a specified time of day.

Note: When using time and date functions, the time returned is the server's system time, which could vary from your local time. You may need to use date_default_timezone_set() if you're server is located in a different timezone.

<?php

    // change your default timezone
        date_default_timezone_set('America/Chicago');

    // get current time of day in unix timestamp
        $currentTime = time();

    // get closing time in unix timestamp
        $closingTime = mktime(16,0,0); // 4pm

    // check if the current time is past closing time
        if($currentTime > $closingTime)
        {
            // current time is greater than the closing time
            // output closed message
                echo "We are curently closed.";
        }
        else
        {
            // current time is less than closing time
            // get hours and minutes left until closing time
                $hoursLeft = gmdate("G", $closingTime - $currentTime);
                $minutesLeft = gmdate("i", $closingTime - $currentTime);

            // output time left before close
                echo $hoursLeft . " hours " . $minutesLeft . " minutes until closing.";
        }

?>

Here we get the current time and define when closing time is. We then see if the current time is greater than closing time. If the current time is greater, then we output the closed message. Otherwise, we can use gmdate() to get the hours and minutes remaining based on the difference between closing time and the current time.

Upvotes: 2

Related Questions