function DateFormatter::formatInterval

Same name and namespace in other branches
  1. 11.x core/lib/Drupal/Core/Datetime/DateFormatter.php \Drupal\Core\Datetime\DateFormatter::formatInterval()
  2. 10 core/lib/Drupal/Core/Datetime/DateFormatter.php \Drupal\Core\Datetime\DateFormatter::formatInterval()
  3. 8.9.x core/lib/Drupal/Core/Datetime/DateFormatter.php \Drupal\Core\Datetime\DateFormatter::formatInterval()

File

core/lib/Drupal/Core/Datetime/DateFormatter.php, line 148

Class

DateFormatter
Provides a service to handle various date related functionality.

Namespace

Drupal\Core\Datetime

Code

public function formatInterval($interval, $granularity = 2, $langcode = NULL) {
  $output = '';
  foreach ($this->units as $key => $value) {
    $key = explode('|', $key);
    if ($interval >= $value) {
      $output .= ($output ? ' ' : '') . $this->formatPlural(floor($interval / $value), $key[0], $key[1], [], [
        'langcode' => $langcode,
      ]);
      $interval %= $value;
      $granularity--;
    }
    elseif ($output) {
      // Break if there was previous output but not any output at this level,
      // to avoid skipping levels and getting output like "1 year 1 second".
      break;

    }
    if ($granularity == 0) {
      break;

    }
  }
  return $output ? $output : $this->t('0 sec', [], [
    'langcode' => $langcode,
  ]);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.