Producing Relative Date/Time from Timestamps in PHP
Introduction
Determining the relative date/time based on a timestamp is a common task in programming. This functionality becomes more complex when considering different time intervals and the direction of the conversion (past or future).
Answer
The function below provides a comprehensive approach to converting Unix timestamps (obtained using the time() function) to relative date/time formats, accounting for both past and future. It generates outputs such as:
The function employs a series of conditional statements to determine the appropriate time representation based on the difference between the current time and the timestamp:
<br>function time2str($ts)<br>{</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">// Handle syntax variations if(!ctype_digit($ts)) $ts = strtotime($ts); // Calculate the difference between now and the timestamp $diff = time() - $ts; // Check for exact matches to simplify handling if($diff == 0) return 'now'; // Handle past timestamps if($diff > 0) { // Calculate day difference $day_diff = floor($diff / 86400); // Format past time intervals switch(true) { case ($day_diff == 0): return constructPastInterval($diff); // Hours, minutes, seconds case ($day_diff == 1): return 'Yesterday'; case ($day_diff < 7): return $day_diff . ' days ago'; case ($day_diff < 31): return ceil($day_diff / 7) . ' weeks ago'; case ($day_diff < 60): return 'last month'; default: return date('F Y', $ts); } } // Handle future timestamps else { // Calculate absolute difference $diff = abs($diff); // Calculate day difference and format future time intervals based on logic similar to the past case. }
}
The constructPastInterval() function is not shown in this response but handles the formatting of past intervals (hours, minutes, seconds).
This function offers a robust and versatile solution for generating relative date/time representations from timestamps, eliminating the need for multiple scripts or complex custom coding.
The above is the detailed content of How Can I Generate Relative Date/Time Strings from Unix Timestamps in PHP?. For more information, please follow other related articles on the PHP Chinese website!