A PHP function to display the time between now and a future date supplied as Unix time, in human readable format, using two blocks of time periods (year, month, week, day, hour or minute.)
function TimeTo($future) // $original should be the future date and time in unix format
{
// Common time periods as an array of arrays
$periods = array(
array(60 * 60 * 24 * 365 , 'year'),
array(60 * 60 * 24 * 30 , 'month'),
array(60 * 60 * 24 * 7, 'week'),
array(60 * 60 * 24 , 'day'),
array(60 * 60 , 'hour'),
array(60 , 'minute'),
);
$today = time();
$since = $future - $today; // Find the difference of time between now and the future
// Loop around the periods, starting with the biggest
for ($i = 0, $j = count($periods); $i < $j; $i++)
{
$seconds = $periods[$i][0];
$name = $periods[$i][1];
// Find the biggest whole period
if (($count = floor($since / $seconds)) != 0)
{
break;
}
}
$print = ($count == 1) ? '1 '.$name : "$count {$name}s";
if ($i + 1 < $j)
{
// Retrieving the second relevant period
$seconds2 = $periods[$i + 1][0];
$name2 = $periods[$i + 1][1];
// Only show it if it's greater than 0
if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0)
{
$print .= ($count2 == 1) ? ', 1 '.$name2 : ", $count2 {$name2}s";
}
}
return $print;
}
echo TimeTo(1359101056);
The provided PHP function, TimeTo
, calculates the time remaining until a specified future date and time, given in Unix timestamp format. Here’s a breakdown of its functionality:
- Function Definition:
function TimeTo($future)
takes$future
, a Unix timestamp representing a future date and time. - Time Periods Array: The
$periods
array contains common time units (year, month, week, day, hour, minute) in seconds. - Calculating Time Difference: The function calculates the time difference
$since
between the current time ($today = time();
) and the future time ($future
). - Finding the Largest Applicable Time Unit: The function loops through
$periods
to find the largest time unit that can be used to express the time until$future
. It breaks out of the loop once it finds this unit. - Formatting the Output: The
$print
variable is set to a string representing the time in the largest unit found, in singular or plural form based on the count. - Adding a Second Time Period: If applicable, the function adds a second, smaller time unit to provide a more precise time description.
- Returning the Result: The function returns the formatted string
$print
, indicating the time remaining until the future date. - Example Usage:
echo TimeTo(1359101056);
prints the time remaining until the Unix timestamp1359101056
.
This function is useful for displaying countdowns or time until future events in a human-readable format.