You are here

public function DateFormatter::formatInterval in Drupal 8

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/Datetime/DateFormatter.php \Drupal\Core\Datetime\DateFormatter::formatInterval()

Formats a time interval with the requested granularity.

Note that for intervals over 30 days, the output is approximate: a "month" is always exactly 30 days, and a "year" is always 365 days. It is not possible to make a more exact representation, given that there is only one input in seconds. If you are formatting an interval between two specific timestamps, use \Drupal\Core\Datetime\DateFormatter::formatDiff() instead.

Parameters

int $interval: The length of the interval in seconds.

int $granularity: (optional) How many different units to display in the string (2 by default).

string|null $langcode: (optional) langcode: The language code for the language used to format the date. Defaults to NULL, which results in the user interface language for the page being used.

Return value

string A translated string representation of the interval.

Overrides DateFormatterInterface::formatInterval

See also

\Drupal\Core\Datetime\DateFormatterInterface::formatDiff()

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,
  ]);
}