Jenssegers\Date\Date::diffForHumans PHP Method

diffForHumans() public method

Get the difference in a human readable format.
public diffForHumans ( Carbon\Carbon $since = null, boolean $absolute = false, $short = false ) : string
$since Carbon\Carbon
$absolute boolean Removes time difference modifiers ago, after, etc
return string
    public function diffForHumans(Carbon $since = null, $absolute = false, $short = false)
    {
        // Get translator
        $lang = $this->getTranslator();
        // Are we comparing against another date?
        $relative = !is_null($since);
        if (is_null($since)) {
            $since = new static('now', $this->getTimezone());
        }
        // Are we comparing to a date in the future?
        $future = $since->getTimestamp() < $this->getTimestamp();
        $units = ['second' => 60, 'minute' => 60, 'hour' => 24, 'day' => 7, 'week' => 30 / 7, 'month' => 12];
        // Date difference
        $difference = abs($since->getTimestamp() - $this->getTimestamp());
        // Default unit
        $unit = 'year';
        // Select the best unit.
        foreach ($units as $key => $value) {
            if ($difference < $value) {
                $unit = $key;
                break;
            }
            $difference = $difference / $value;
        }
        $difference = floor($difference);
        // Select the suffix.
        if ($relative) {
            $suffix = $future ? 'after' : 'before';
        } else {
            $suffix = $future ? 'from_now' : 'ago';
        }
        // Some languages have different unit translations when used in combination
        // with a specific suffix. Here we will check if there is an optional
        // translation for that specific suffix and use it if it exists.
        if ($lang->trans("{$unit}_diff") != "{$unit}_diff") {
            $ago = $lang->transChoice("{$unit}_diff", $difference, [':count' => $difference]);
        } elseif ($lang->trans("{$unit}_{$suffix}") != "{$unit}_{$suffix}") {
            $ago = $lang->transChoice("{$unit}_{$suffix}", $difference, [':count' => $difference]);
        } else {
            $ago = $lang->transChoice($unit, $difference, [':count' => $difference]);
        }
        if ($absolute) {
            return $ago;
        }
        return $lang->transChoice($suffix, $difference, [':time' => $ago]);
    }

Usage Example

Beispiel #1
-1
 public function getDataPostagemDiffAttribute()
 {
     $date = new Date($this->created_at);
     return $date->diffForHumans();
 }