Here is a Twitter style PHP time interval calculation function that will return the time difference between two dates in days, hours, minutes or seconds depending on the time interval between the two times.
If the time interval is within 60 seconds, then ‘X seconds ago’ will be displayed. If the interval is between 60 seconds and 60 minutes then ‘X minutes ago’ will appear. Similarly, ‘X hours ago’ will be displayed for a time interval greater than 60 minutes but less than 24 hours and ‘X days ago’ for anything above 24 hours.
The time interval function takes in three arguments:
- The old date – the initial date\time in the standard MySQL format i.e. “Y-m-d H:i:s”
- The new date – again, in the format “Y-m-d H:i:s”. To use the current ‘now’ time, pass date(“Y-m-d H:i:s”) as the argument
- The time interval type. If you want the function to return the most appropriate unit of time automatically, use ‘x’ but this could be overridden by specifying the values for seconds, minutes, hours or days using the values ‘s’, ‘m’, ‘h’ or ‘d’ respectively.
Here is the PHP time interval function:
<?php function xTimeAgo ($oldTime, $newTime, $timeType) { $timeCalc = strtotime($newTime) - strtotime($oldTime); if ($timeType == "x") { if ($timeCalc = 60)) { $timeType = "m"; } if ($timeCalc = (60*60))) { $timeType = "h"; } if ($timeCalc = (60*60*24))) { $timeType = "d"; } } if ($timeType == "s") { $timeCalc .= " seconds ago"; } if ($timeType == "m") { $timeCalc = round($timeCalc/60) . " minutes ago"; } if ($timeType == "h") { $timeCalc = round($timeCalc/60/60) . " hours ago"; } if ($timeType == "d") { $timeCalc = round($timeCalc/60/60/24) . " days ago"; } return $timeCalc; } ?>
The following example calls this function, passing 3 arguments for old date (MySQL datetime field from a recordset), new date (current time) and time type (x for automatic).
<?php echo xTimeAgo($row_rsRecordset1['dateField'], date("Y-m-d H:i:s"), "x"); ?>
The resulting time string should appear as ‘X seconds ago’ or ‘X minutes ago’ etc depending on the time interval.