Unknown timediff filter error

Submitted on

The time_diff filter is not a built-in Twig filter in Drupal 9. To achieve the desired functionality, you need to create a custom Twig filter.

Here's a step-by-step guide on how to add a custom time_diff filter in your Drupal 9 site:

Step 1: Create a Custom Module

First, create a custom module. For example, let's name it custom_twig_filters.

1. Create the module directory and files:

/modules/custom/custom_twig_filters/

Inside this directory, create the following files:

custom_twig_filters.info.yml custom_twig_filters.module src/TwigExtension/TimeDiffExtension.php

2. Define the module in custom_twig_filters.info.yml:

name: 'Custom Twig Filters' type: module description: 'Provides custom Twig filters.' core_version_requirement: ^8 || ^9 package: Custom dependencies:  - drupal:twig_tweak

3. Implement the hook in custom_twig_filters.module:

<?php 
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
 function custom_twig_filters_theme_suggestions_HOOK_alter(array &$suggestions, array $variables) {  
   // Your code here if needed.
 }


Step 2: Create the Custom Twig Extension

Now, implement the custom Twig extension that includes the time_diff filter.

1. Create the TimeDiffExtension.php file in the src/TwigExtension directory:

<?php
namespace Drupal\custom_twig_filters\TwigExtension;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Drupal\Component\Datetime\TimeInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
 * Provides a "time_diff" Twig filter.
 */
class TimeDiffExtension extends AbstractExtension {
  /**
   * The time service.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  protected $time;
  /**
   * Constructs a new TimeDiffExtension object.
   *
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The time service.
   */
  public function __construct(TimeInterface $time) {
    $this->time = $time;
  }
 
  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('datetime.time')
    );
  }
  /**
   * {@inheritdoc}
   */
  public function getFilters() {
    return [
      new TwigFilter('time_diff', [$this, 'calculateTimeDiff']),
    ];
  }
  
  /**
   * Calculate the difference between the current time and the given timestamp.
   *
   * @param int $timestamp
   *   The timestamp to compare against the current time.
   *
   * @return string
   *   The formatted time difference.
   */
  public function calculateTimeDiff($timestamp) {
    $current_time = $this->time->getCurrentTime();
    $diff = $current_time - $timestamp;
    if ($diff < 60) {
      return t('@count seconds ago', ['@count' => $diff]);
    }
    elseif ($diff < 3600) {
      $minutes = floor($diff / 60);
      return t('@count minutes ago', ['@count' => $minutes]);
    }
    elseif ($diff < 86400) {
      $hours = floor($diff / 3600);
      return t('@count hours ago', ['@count' => $hours]);
    }
    else {
      $days = floor($diff / 86400);
      return t('@count days ago', ['@count' => $days]);
    }
  }
  /**
   * {@inheritdoc}
   */
  public function getName() {
    return 'time_diff_extension';
  }
}


Step 3: Register the Twig Extension 

Finally, register the Twig extension by creating a service definition. 

Create custom_twig_filters.services.yml in the module root: 

services: 
  custom_twig_filters.time_diff_extension: 
    class: Drupal\custom_twig_filters\TwigExtension\TimeDiffExtension 
    arguments: ['@datetime.time'] 
    tags: 
      - { name: twig.extension }


Step 4: Clear Cache

Usage in Twig Template

Now you can use the time_diff filter in your Twig templates:

{{ field_event_due_1|time_diff }}

This should resolve the error and allow you to use the time_diff filter as intended.