You are here

public function DurationService::getHumanReadableStringFromDateInterval in Duration Field 3.0.x

Same name and namespace in other branches
  1. 8.2 src/Service/DurationService.php \Drupal\duration_field\Service\DurationService::getHumanReadableStringFromDateInterval()

Get a human-readable string representing a DateTime interval.

Parameters

\DateInterval $dateInterval: The PHP DateInterval for which a human-readable value should be extracted.

array $granularity: An array containing the following keys:

  • y (year)
  • m (month)
  • d (day)
  • h (hour)
  • i (minute)
  • s (second)

Each key should be set to TRUE or FALSE to indicate whether or not the value should be displayed.

string $separator: The separator that should be inserted between each time element value of the interval.

string $textLength: The length of text that should be returned. Allowed values are 'full' and 'short'.

Return value

string A human readable translated string representing the DateInterval element.

Overrides DurationServiceInterface::getHumanReadableStringFromDateInterval

File

src/Service/DurationService.php, line 122

Class

DurationService
Provides services for the Duration Field module.

Namespace

Drupal\duration_field\Service

Code

public function getHumanReadableStringFromDateInterval(DateInterval $dateInterval, array $granularity, $separator = ' ', $textLength = 'full') {
  $output = [];
  if ($granularity['y'] && ($years = $dateInterval
    ->format('%y'))) {
    $output[] = $this
      ->getTimePeriod('year', $years, $textLength);
  }
  if ($granularity['m'] && ($months = $dateInterval
    ->format('%m'))) {
    $output[] = $this
      ->getTimePeriod('month', $months, $textLength);
  }
  if ($granularity['d'] && ($days = $dateInterval
    ->format('%d'))) {
    $output[] = $this
      ->getTimePeriod('day', $days, $textLength);
  }
  if ($granularity['h'] && ($hours = $dateInterval
    ->format('%h'))) {
    $output[] = $this
      ->getTimePeriod('hour', $hours, $textLength);
  }
  if ($granularity['i'] && ($minutes = $dateInterval
    ->format('%i'))) {
    $output[] = $this
      ->getTimePeriod('minute', $minutes, $textLength);
  }
  if ($granularity['s'] && ($seconds = $dateInterval
    ->format('%s'))) {
    $output[] = $this
      ->getTimePeriod('second', $seconds, $textLength);
  }
  return count($output) ? implode($separator, $output) : $this
    ->t('Empty');
}