PHP code example of knplabs / knp-time-bundle

1. Go to this page and download the library: Download knplabs/knp-time-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

knplabs / knp-time-bundle example snippets


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

public function yourAction(DateTimeFormatter $dateTimeFormatter)
{
    $someDate = new \DateTimeImmutable('-2 years'); // or $entity->publishedDate()
    $toDate = new \DateTimeImmutable('now');

    $agoTime = $dateTimeFormatter->formatDiff($someDate, $toDate); // $toDate parameter is optional and defaults to "now"

    $readTime = $dateTimeFormatter->formatDuration(64); // or $entity->readTimeInSeconds()

    $ageTime = $dateTimeFormatter->formatAge($someDate, $toDate); // $toDate parameter is optional and defaults to "now"

    return $this->json([
        //  ...
        'published_at' => $agoTime, // 2 years ago
        'read_time' => $readTime, // 1 minute
        // ...
    ]);
}
twig
Last edited: {{ post.updatedAt|time_diff }} <!-- Last edited: 1 week ago -->

Event date: {{ event.date|time_diff }} <!-- Event date: in two weeks -->

Read time: {{ post.readTimeInSeconds|duration }} <!-- Read time: 2 minutes -->

Age: {{ user.birthdate|age }} <!-- Age: 30 years old -->
twig
{# with filter: #}
Age: {{ user.birthdate|age }} {# Age: 30 years old #}

{# ... or use the equivalent function: #}
Age: {{ age(user.birthdate) }} {# Age: 30 years old #}
twig
{{ someDateTimeVariable|time_diff(locale='es') }}

{{ someDurationInSeconds|duration(locale='es') }}

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