TimeAgo.php 2.32 KB
<?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;
    }
}