How to make a countdown using PHP
One way to make a countdown using PHP is to use the time()
function, which returns the current timestamp, and subtract a future timestamp (representing the end date and time of the countdown) from it. You can then use the date()
function to format the remaining time into days, hours, minutes, and seconds. Here is an example:
<?php
$end_time = strtotime("2022-12-31 23:59:59"); // Countdown end time
$current_time = time(); // Current timestamp
$time_left = $end_time - $current_time; // Time remaining in seconds
$days = floor($time_left / 86400); // 86400 seconds in a day
$time_left = $time_left % 86400;
$hours = floor($time_left / 3600); // 3600 seconds in an hour
$time_left = $time_left % 3600;
$minutes = floor($time_left / 60); // 60 seconds in a minute
$seconds = $time_left % 60;
echo "Time remaining until 2022-12-31 23:59:59: $days days, $hours hours, $minutes minutes, and $seconds seconds.";
Watch a video course
Learn object oriented PHP
You can also use the DateTime object with the diff function to get the difference between the current time and the end time in a more readable format like this:
<?php
$end_time = new DateTime("2022-12-31 23:59:59");
$current_time = new DateTime();
$interval = $current_time->diff($end_time);
if ($interval->invert) {
echo "The end date has already passed.";
} else {
echo $interval->format("Time left until 2022-12-31 23:59:59: %a days, %h hours, %i minutes, and %s seconds.");
}
Note that you need to use the DateTime function that is available in PHP >= 5.2.0