knplabs/knp-time-bundle

Making your dates look sensible and descriptive

Installs: 4 679 607

Dependents: 36

Suggesters: 3

Security: 0

Stars: 543

Watchers: 38

Forks: 100

Open Issues: 5

Type:symfony-bundle

v1.20.0 2022-10-11 15:32 UTC

README

This bundle does one simple job: takes dates and gives you friendly "2 hours ago"-type messages. Woh!

Last edited {{ post.updatedAt|ago }}
<-- Last edited 1 week ago -->

Want to see it used in a screencast 🎥? Check out SymfonyCasts: https://symfonycasts.com/screencast/symfony-doctrine/ago

The date formatted can be translated into any language, and many are supported out of the box.

INSTALLATION

Use Composer to install the library:

composer require knplabs/knp-time-bundle

Woo! You did it! Assuming your project uses Symfony Flex, the bundle should be configured and ready to go. If not, you can enable Knp\Bundle\TimeBundle\KnpTimeBundle manually.

USAGE

In Twig:

{{ someDateTimeVariable|ago }}

... or use the equivalent function:
{{ time_diff(someDateTimeVariable) }}

Note: the "ago" filter works fine for dates in the future, too.

In controllers

You can also "ago" dates inside PHP by autowiring the Knp\Bundle\TimeBundle\DateTimeFormatter service:

use Knp\Bundle\TimeBundle\DateTimeFormatter;
// ...

public function yourAction(DateTimeFormatter $dateTimeFormatter)
{
    $someDate = new \DateTime('2017-02-11'); //or $entity->publishedDate()
    $now = new \DateTime();
    
    $agoTime = $dateTimeFormatter->formatDiff($someDate, $now);
    return $this->json([
        ...
        'published_at' => $agoTime
        ...
    ]);
}

Controlling the Translation Locale

The bundle will automatically use the current locale when translating the "ago" messages. However, you can override the locale:

{{ someDateTimeVariable|ago(locale='es') }}

TESTS

If you want to run tests, please check that you have installed dev dependencies.

./vendor/bin/simple-phpunit

Maintainers

Anyone can contribute to this repository (and it's warmly welcomed!). The following people maintain and can merge into this library: