Change record status: 
Project: 
Introduced in branch: 
8.0.x
Description: 

Since formatInterval() in Drupal\Core\Datetime\DateFormatter is not accurate for intervals larger than a month, a new method DateFormatter::formatDiff() was added. It calculates the time difference between a $from and a $to timestamp, and returns a translated string representation of that interval.

Several options can be passed:

  • granularity: An integer value that signals how many different units to display in the string. Defaults to 2.
  • langcode: A string representing a language code. It is used to translate to a language other than what is used to display the page. Defaults to NULL, which results in the current user language being used.
  • strict: A Boolean value indicating whether or not the $from timestamp can be after the $to timestamp. If TRUE (default) and $from is after $to, the result string will be "0 seconds". If FALSE and $from is after $to, the result string will be the formatted time difference.

Example usage:

$from = \DateTime::createFromFormat('Y-m-d G:i:s', '2013-11-11 09:08:07')->getTimestamp();
$to = \DateTime::createFromFormat('Y-m-d G:i:s', '2013-12-11 10:09:08')->getTimestamp();

$diff = $this->dateFormatter->formatDiff($from, $to, ['granularity' => 3, 'langcode' => 'en', 'strict' => TRUE]);
// $diff would evaluate to '1 month 1 hour 1 minute'

Because a diff is always taken from two timestamps, two convenience wrappers were added to compare values against the current request time: formatTimeDiffSince() and formatTimeDiffUntil(). The former calculates the time difference from the given $timestamp to the current request time, while the latter calculates the time difference from the current request time to the given $timestamp. They both take the same $options as the formatDiff() method above.

Example usage:

// Given a request time \DateTime::createFromFormat('Y-m-d G:i:s', '2013-11-11 09:08:08')->getTimestamp();

$timestamp = \DateTime::formatDiff('Y-m-d G:i:s', '2013-11-11 09:08:07')->getTimestamp();
$diff = $this->dateFormatter->formatTimeDiffSince($timestamp, ['granularity' => 3, 'langcode' => 'en', 'strict' => FALSE]);
// $diff would evaluate to '1 second'

$timestamp = \DateTime::formatDiff('Y-m-d G:i:s', '2013-11-11 09:08:09')->getTimestamp();
$diff = $this->dateFormatter->formatTimeDiffUntil($timestamp, ['granularity' => 1, 'langcode' => 'en', 'strict' => TRUE]);
// $diff would evaluate to '1 second'

Impacts: 
Module developers