Custom version of DateFormatter service I want to create a slightly different version of the formatInterval function. Normally I do this:

echo \Drupal::service('date.formatter')-&gt;formatInterval($seconds);


I want the final string to say not "1 hour 40 minutes", but "1h 40m" instead, so I was thinking about making a subclass of the core's DateFormatter class, and just change the protected $units property to define what I want.

How do I do this elegantly in a custom module, "the Drupal way"?
The full story can be found at Altering existing services, providing dynamic services, but essentially you need to add a service provider to your module, e.g. (mostly copied from the d.o page above):

namespace Drupal\my_module;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

/**
 * Modifies the date formatter service.
 */
class MyModuleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    // Overrides date.formatter class for custom interval formatting.
    $definition = $container-&gt;getDefinition('date.formatter');
    $definition-&gt;setClass(DateFormatter::class);
  }
}


(assuming your replacement class is \Drupal\my_module\DateFormatter)