note 99393 deleted from function.time by cmb
| From: | cmb@php.net | Date: | Sun, 01 Aug 2021 14:56:45 +0000 |
| Subject: | note 99393 deleted from function.time by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-216709@lists.php.net to get a copy of this message | ||
Note Submitter: John Galt
----
This is another function to calculate the difference between two times and output it in a relative
format. This one, however, combines various units. In other words, it will return "3 days, 2
hours, 6 minutes, and 2 seconds ago" instead of "3 days ago."
Please bear in mind that it is intended for times that are very close together. It will not be
accurate for calculating dates more than a month apart. This is because one of the units it relies
on is "weeks," which do not correspond directly with months. What I'm trying to get
across is, the program assumes that a month is precisely 4 weeks long, i.e. 28 days. This also means
that a "year" according to this function is 336 days.
<?php
function rel_time($from, $to = null)
{
$to = (($to === null) ? (time()) : ($to));
$to = ((is_int($to)) ? ($to) : (strtotime($to)));
$from = ((is_int($from)) ? ($from) : (strtotime($from)));
$units = array
(
"year" => 29030400, // seconds in a year (12 months)
"month" => 2419200, // seconds in a month (4 weeks)
"week" => 604800, // seconds in a week (7 days)
"day" => 86400, // seconds in a day (24 hours)
"hour" => 3600, // seconds in an hour (60 minutes)
"minute" => 60, // seconds in a minute (60 seconds)
"second" => 1 // 1 second
);
$diff = abs($from - $to);
$suffix = (($from > $to) ? ("from now") : ("ago"));
foreach($units as $unit => $mult)
if($diff >= $mult)
{
$and = (($mult != 1) ? ("") : ("and "));
$output .= ", ".$and.intval($diff / $mult)." ".$unit.((intval($diff / $mult)
== 1) ? ("") : ("s"));
$diff -= intval($diff / $mult) * $mult;
}
$output .= " ".$suffix;
$output = substr($output, strlen(", "));
return $output;
}
?>
The function rel_time() accepts two parameters: $from and $to. For best results, provide them as
UNIX timestamps (derived from PHP's time() function). They also accept formats supported by
strtotime(). $to is an optional argument and defaults to the current time.
The function will calculate the difference between $from and $to. If $from occurs after $to, the
function will substitue "ago" with "from now."
Example usage:
<?php
echo rel_time("September 2, 2010 4:20 PM");
// returns "2 weeks, 4 days, 23 hours, 25 minutes, and 3 seconds from now"
?>