From 3cbdbd7f197d076709641e83b41814b8c6a855ea Mon Sep 17 00:00:00 2001 From: Camil Staps Date: Mon, 1 Aug 2016 00:23:24 +0200 Subject: Implement $relatively for formatting dates --- classes/BusinessAdmin.php | 54 +++++++++++++++++++++++++++++++++++------------ 1 file changed, 40 insertions(+), 14 deletions(-) (limited to 'classes/BusinessAdmin.php') diff --git a/classes/BusinessAdmin.php b/classes/BusinessAdmin.php index 83fa4b3..1ea02ae 100644 --- a/classes/BusinessAdmin.php +++ b/classes/BusinessAdmin.php @@ -431,32 +431,58 @@ class BusinessAdmin { /** * Format a date nicely * - * @todo implement $relatively = true - * * @param int $timestamp The UNIX timestamp to format * @param bool $with_time If false, only the date is returned; if false, also the time * @param bool $full_date If true, a year will be outputted even if the date is in the current year - * @param bool $relatively Whether or not to show the date relatively (e.g. '1 day ago') (NOT IMPLEMENTED YET) + * @param bool $relatively Whether or not to show the date relatively (e.g. '1 day ago') * * @return string The formatted date */ public static function formatDate($timestamp, $with_time = true, $full_date = false, $relatively = false) { - $output = ''; - if (date('Y', $timestamp) == 1970) { - return 'never'; + if ($relatively) { + $delta = time() - $timestamp; + $second = 1; + $minute = 60 * $second; + $hour = 60 * $minute; + $day = 24 * $hour; + $month = 30 * $day; + $year = 365 * $day; + if ($delta < 2 * $minute) + return 'just now'; + if ($delta < 45 * $minute) + return floor($delta / $minute) . ' minutes ago'; + if ($delta < 90 * $minute) + return 'an hour ago'; + if ($delta < 24 * $hour) + return floor($delta / $hour) . ' hours ago'; + if ($delta < 48 * $hour) + return 'yesterday'; + if ($delta < 30 * $day) + return floor($delta / $day) . ' days ago'; + + $output = []; + $years = floor($delta / $year); + if ($years != 0) + $output[] = $years == 1 ? 'one year' : $years . ' years'; + $delta -= $years * $year; + $months = floor($delta / $month); + if ($months != 0) + $output[] = $months == 1 ? 'one month' : $months . ' months'; + return implode(', ', $output); } - if (date('d/m/Y') == date('d/m/Y', $timestamp)) { + + if (date('Y', $timestamp) == 1970) + return 'never'; + if (date('d/m/Y') == date('d/m/Y', $timestamp)) return 'today'; - } - if (date('Y') != date('Y', $timestamp) || $full_date) { + + $output = ''; + if (date('Y') != date('Y', $timestamp) || $full_date) $output .= date('Y-', $timestamp); - } - if (date('d/m/Y') != date('d/m/Y', $timestamp) || $full_date) { + if (date('d/m/Y') != date('d/m/Y', $timestamp) || $full_date) $output .= date('m-d', $timestamp); - } - if ($with_time) { + if ($with_time) $output .= date(' H:i', $timestamp); - } return $output; } -- cgit v1.2.3