Skip to main content
added example code
Source Link
avpaderno
  • 97.9k
  • 15
  • 164
  • 284

The code contains two errors, since Drupal 8

  • doesn't have any date service
  • doesn't define any drupal_map_assoc() function

The equivalent of Drupal 7 format_interval($interval, $granularity = 2, $langcode = NULL) is \Drupal::service('date.formatter')->formatInterval($interval, $granularity = 2, $langcode = NULL), which also works on Drupal 8.0.x.

If you need to write code that given an array like [30, 60] returns an array like [30 => '30 seconds ago', 60 => '1 minute ago'], this is the code I would use.

$time_intervals = [30, 3600, 10800, 21600, 43200, 86400, 172800, 259200, 604800, 1209600, 2592000, 5184000, 7776000];

$options = build_options($time_intervals);

function build_options(array $time_intervals, $granularity = 2, $langcode = NULL) {
  $callback = function ($value) use ($granularity, $langcode) {
    return \Drupal::service('date.formatter')->formatInterval($value, $granularity, $langcode);
  };

  return array_combine($time_intervals, array_map($callback, $time_intervals));
}

The code contains two errors, since Drupal 8

  • doesn't have any date service
  • doesn't define any drupal_map_assoc() function

The equivalent of Drupal 7 format_interval($interval, $granularity = 2, $langcode = NULL) is \Drupal::service('date.formatter')->formatInterval($interval, $granularity = 2, $langcode = NULL), which also works on Drupal 8.0.x.

The code contains two errors, since Drupal 8

  • doesn't have any date service
  • doesn't define any drupal_map_assoc() function

The equivalent of Drupal 7 format_interval($interval, $granularity = 2, $langcode = NULL) is \Drupal::service('date.formatter')->formatInterval($interval, $granularity = 2, $langcode = NULL), which also works on Drupal 8.0.x.

If you need to write code that given an array like [30, 60] returns an array like [30 => '30 seconds ago', 60 => '1 minute ago'], this is the code I would use.

$time_intervals = [30, 3600, 10800, 21600, 43200, 86400, 172800, 259200, 604800, 1209600, 2592000, 5184000, 7776000];

$options = build_options($time_intervals);

function build_options(array $time_intervals, $granularity = 2, $langcode = NULL) {
  $callback = function ($value) use ($granularity, $langcode) {
    return \Drupal::service('date.formatter')->formatInterval($value, $granularity, $langcode);
  };

  return array_combine($time_intervals, array_map($callback, $time_intervals));
}
Source Link
avpaderno
  • 97.9k
  • 15
  • 164
  • 284

The code contains two errors, since Drupal 8

  • doesn't have any date service
  • doesn't define any drupal_map_assoc() function

The equivalent of Drupal 7 format_interval($interval, $granularity = 2, $langcode = NULL) is \Drupal::service('date.formatter')->formatInterval($interval, $granularity = 2, $langcode = NULL), which also works on Drupal 8.0.x.