Home >Backend Development >PHP Tutorial >How to Convert Timestamps to Human-Readable Relative Dates and Times in PHP?
In PHP, you can easily convert timestamps to user-friendly relative date/time strings that work for both past and future timestamps. By adapting timestamps to this format, you can enhance the user experience by providing intuitive time representations.
To accomplish this conversion, you can utilize the following function:
function time2str($ts) { // Handle non-numeric timestamps if (!ctype_digit($ts)) { $ts = strtotime($ts); } $diff = time() - $ts; // Handle current time if ($diff == 0) { return 'now'; } // Handle past timestamps if ($diff > 0) { $day_diff = floor($diff / 86400); if ($day_diff == 0) { // Handle minutes and hours ago if ($diff < 60) { return 'just now'; } elseif ($diff < 120) { return '1 minute ago'; } elseif ($diff < 3600) { return floor($diff / 60) . ' minutes ago'; } elseif ($diff < 7200) { return '1 hour ago'; } elseif ($diff < 86400) { return floor($diff / 3600) . ' hours ago'; } } elseif ($day_diff == 1) { return 'Yesterday'; } elseif ($day_diff < 7) { return $day_diff . ' days ago'; } elseif ($day_diff < 31) { return ceil($day_diff / 7) . ' weeks ago'; } elseif ($day_diff < 60) { return 'last month'; } else { return date('F Y', $ts); } } // Handle future timestamps else { $diff = abs($diff); $day_diff = floor($diff / 86400); if ($day_diff == 0) { // Handle minutes and hours from now if ($diff < 120) { return 'in a minute'; } elseif ($diff < 3600) { return 'in ' . floor($diff / 60) . ' minutes'; } elseif ($diff < 7200) { return 'in an hour'; } elseif ($diff < 86400) { return 'in ' . floor($diff / 3600) . ' hours'; } } elseif ($day_diff == 1) { return 'Tomorrow'; } elseif ($day_diff < 4) { return date('l', $ts); } elseif ($day_diff < 7 + (7 - date('w'))) { return 'next week'; } elseif (ceil($day_diff / 7) < 4) { return 'in ' . ceil($day_diff / 7) . ' weeks'; } elseif (date('n', $ts) == date('n') + 1) { return 'next month'; } else { return date('F Y', $ts); } } }
By using this function, you can easily generate user-friendly relative date/time strings from timestamps.
The above is the detailed content of How to Convert Timestamps to Human-Readable Relative Dates and Times in PHP?. For more information, please follow other related articles on the PHP Chinese website!