Blame view
app/Support/Helpers/TimeAgo.php
2.32 KB
e77200db5 Initial commit |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
<?php namespace FootyRoom\Support\Helpers; use DateTime; class TimeAgo { /** * Returns a human friendly time ago string. * * For times within last 24 hours it just returns "Today" and for others a * simple "x days ago", "x months ago" and "x years ago". * * @param string $date Any time string that strtotime() can recognize. * * @return string */ public static function from($date): string { $diff = time() - strtotime($date); if ($diff < 86400) { return 'Today'; } else { return self::between($diff) . ' ago'; } } /** * Returns difference between two times in human friendly format. * * This method can also be used to express time duration in a human readable * format if first parameter is passed as integer representing duration as * seconds and second parameter is either omitted or set to 0 (zero). * * @param \DateTime|int $dateA * @param \DateTime|int $dateB * * @return string */ public static function between($dateA, $dateB = 0): string { if ($dateA instanceof DateTime) { $timestampA = $dateA->getTimestamp(); } else { $timestampA = $dateA; } if ($dateB instanceof DateTime) { $timestampB = $dateB->getTimestamp(); } else { $timestampB = $dateB; } if ($timestampA >= $timestampB) { $diff = $timestampA - $timestampB; } else { $diff = $timestampB - $timestampA; } if ($diff < 3600) { $minutes = round($diff / 60); $timeAgo = $minutes.' minute'.($minutes < 2 ? '' : 's'); } elseif ($diff < 86400) { $hours = round($diff / 3600); $timeAgo = $hours.' hour'.($hours < 2 ? '' : 's'); } elseif ($diff < 2592000) { $days = round($diff / 86400); $timeAgo = $days.' day'.($days < 2 ? '' : 's'); } elseif ($diff < 31536000) { $months = round($diff / 2592000); $timeAgo = $months.' month'.($months < 2 ? '' : 's'); } elseif ($diff >= 31536000) { $years = round($diff / 31536000); $timeAgo = $years.' year'.($years < 2 ? '' : 's'); } return $timeAgo; } } |