W3cubDocs

/Drupal 8

public function DateFormatter::formatInterval

public DateFormatter::formatInterval($interval, $granularity = 2, $langcode = NULL)

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 144

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], array(), array('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', array(), array('langcode' => $langcode));
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Datetime!DateFormatter.php/function/DateFormatter::formatInterval/8.1.x