Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Knp Time Bundle Laravel Package

knplabs/knp-time-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require knplabs/knp-time-bundle
    

    If not using Symfony Flex, manually enable the bundle in config/bundles.php:

    return [
        // ...
        Knp\Bundle\TimeBundle\KnpTimeBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Display a human-readable time difference in Twig:

    {{ post.updatedAt|time_diff }}  {# Output: "5 minutes ago" #}
    
  3. Check Configuration: Verify default settings in config/packages/knp_time.yaml (e.g., default_locale, formats).


Implementation Patterns

Core Workflows

  1. Time Differences in Twig:

    • Use |time_diff or |ago for past/future dates:
      {{ event.date|time_diff }}  {# "in 3 days" #}
      {{ post.createdAt|ago }}     {# "2 hours ago" #}
      
    • Pass custom formats via time_diff(someDate, 'F j, Y').
  2. Duration Formatting:

    • Convert seconds to human-readable strings:
      {{ post.readTimeInSeconds|duration }}  {# "1 minute 30 seconds" #}
      
    • Customize precision with duration(seconds, 2) (e.g., "1m 30s").
  3. Age Calculation:

    • Format birthdates as ages:
      {{ user.birthdate|age }}  {# "30 years old" #}
      
    • Use age() function in Twig or KnpTime::age() in PHP.
  4. PHP Integration:

    • Use the KnpTime service in controllers/services:
      $timeDiff = $this->get('knp_time')->diff($dateTime);
      $duration = $this->get('knp_time')->duration($seconds);
      
  5. Translation:

    • Leverage built-in translations (e.g., ago, in, years old).
    • Override translations in translations/messages.{locale}.yml:
      knp_time:
        ago: "vor"
        in: "in"
      

Integration Tips

  • Doctrine Entities: Use with DateTime fields directly in Twig templates. Example:

    // Entity
    #[ORM\Column(type: 'datetime')]
    private $publishedAt;
    
    {{ article.publishedAt|time_diff }}  {# "yesterday" #}
    
  • API Responses: Format dates in JSON responses using Symfony’s Serializer with custom normalizers:

    # config/packages/serializer.yaml
    Knp\Bundle\TimeBundle\Serializer\TimeDiffNormalizer:
      format: 'time_diff'
    
  • Custom Formats: Extend formats in config/packages/knp_time.yaml:

    knp_time:
      format: 'F j, Y \a\t g:i a'  {# "January 1, 2023 at 2:30 pm" #}
    

Gotchas and Tips

Pitfalls

  1. Locale Mismatches:

    • Ensure default_locale in knp_time.yaml matches your app’s locale.
    • Debug: Check {{ app.request.locale }} in Twig to confirm active locale.
  2. Timezones:

    • Time differences respect the DateTime object’s timezone. Use setTimezone() if needed:
      $dateTime->setTimezone(new \DateTimeZone('UTC'));
      
  3. Future Dates:

    • |time_diff works for future dates but defaults to "in X" phrasing. Override translations if needed.
  4. Caching:

    • Translations are cached. Clear cache after customizing:
      php bin/console cache:clear
      
  5. Edge Cases:

    • Zero-second durations render as 0 seconds. Handle in templates:
      {% if post.readTimeInSeconds > 0 %}
          {{ post.readTimeInSeconds|duration }}
      {% else %}
          Instant!
      {% endif %}
      

Debugging

  • Check Available Filters: Dump Twig filters to verify registration:

    {{ dump(_twig_filters) }}
    

    Look for time_diff, ago, duration, and age.

  • Log Time Calculations: Debug DateTime objects in PHP:

    \Log::debug('DateTime:', ['date' => $dateTime, 'timezone' => $dateTime->getTimezone()]);
    
  • Translation Debugging: Use Symfony’s translation dumper:

    php bin/console debug:translation knp_time
    

Extension Points

  1. Custom Time Diff Logic: Extend the TimeDiff class:

    // src/Service/CustomTimeDiff.php
    use Knp\Time\TimeDiff;
    
    class CustomTimeDiff extends TimeDiff {
        public function getDiffString(\DateTimeInterface $dateTime): string {
            // Custom logic
            return parent::getDiffString($dateTime);
        }
    }
    

    Register as a service:

    # config/services.yaml
    Knp\Bundle\TimeBundle\Twig\Extension\TimeExtension:
        arguments:
            $timeDiff: '@custom_time_diff'
    
  2. Add New Duration Units: Modify the Duration class or create a decorator:

    // src/Service/CustomDuration.php
    use Knp\Time\Duration;
    
    class CustomDuration extends Duration {
        protected function getUnits(): array {
            return array_merge(parent::getUnits(), ['decades' => 36525]);
        }
    }
    
  3. Twig Extensions: Add custom filters/functions to TimeExtension:

    // src/Twig/CustomTimeExtension.php
    use Knp\Bundle\TimeBundle\Twig\Extension\TimeExtension;
    
    class CustomTimeExtension extends TimeExtension {
        public function getFunctions() {
            return array_merge(parent::getFunctions(), [
                new \Twig\TwigFunction('custom_duration', [$this->duration, 'format']),
            ]);
        }
    }
    

    Register the extension in services.yaml.

  4. Configuration Overrides: Dynamically adjust formats per environment:

    # config/packages/knp_time.yaml
    when@prod:
        knp_time:
            format: 'Y-m-d'  {# Simpler format in production #}
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware