You are here

public function TwigDate::diff in Bamboo Twig 8.3

Same name and namespace in other branches
  1. 8.5 bamboo_twig_extensions/src/TwigExtension/TwigDate.php \Drupal\bamboo_twig_extensions\TwigExtension\TwigDate::diff()
  2. 8.2 bamboo_twig_extensions/src/TwigExtension/TwigDate.php \Drupal\bamboo_twig_extensions\TwigExtension\TwigDate::diff()
  3. 8.4 bamboo_twig_extensions/src/TwigExtension/TwigDate.php \Drupal\bamboo_twig_extensions\TwigExtension\TwigDate::diff()

Filter for converting dates to a time ago string.

Parameters

\Drupal\Core\Template\TwigEnvironment $env: A Twig_Environment instance.

string|DateTime $date: String or DateTime object to convert.

string|DateTime $now: String or DateTime object to compare with. If none given, the current time will be used.

string $unit: The returned unit. By default, it will use the most efficient unit.

bool $humanize: The returned value will be human readable. If none given, the current time will be used.

Return value

string|int The converted time. The results as string or integer depend of the $humanize param.

File

bamboo_twig_extensions/src/TwigExtension/TwigDate.php, line 61

Class

TwigDate
Provides bridge for Text functions and filters.

Namespace

Drupal\bamboo_twig_extensions\TwigExtension

Code

public function diff(TwigEnvironment $env, $date, $now = NULL, $unit = NULL, $humanize = TRUE) {

  // Convert both dates to DateTime instances.
  $date = twig_date_converter($env, $date);
  $now = twig_date_converter($env, $now);

  // Get the difference between the two DateTime objects.
  $diff = $date
    ->diff($now);
  $count = 0;

  // Check existing units.
  if ($unit != NULL && array_key_exists($unit, self::$units)) {
    $count = $this
      ->getIntervalUnits($diff, $unit);
    $duration = self::$units[$unit];
  }
  else {

    // Check for each interval if it appears in the $diff object.
    foreach (self::$units as $attribute => $duration) {
      $count = $diff->{$attribute};
      if (0 !== $count) {
        break;
      }
    }
  }
  if ($humanize) {
    return $this
      ->humanize($count, $diff->invert, $duration);
  }
  return $diff->invert ? $count : $count * -1;
}