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

Date Converter Bundle Laravel Package

artur-gajewski/date-converter-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer
    composer require artur-gajewski/date-converter-bundle:1.0.*@dev
    
  2. Register the Bundle Add to app/AppKernel.php:
    new Aga\DateConverterBundle\DateConverterBundle(),
    
  3. Enable Twig Extension Add to app/config/services.yml:
    services:
        aga_dateconverter.twig.extension:
            class: Aga\DateConverterBundle\Extension\DateConverterTwigExtension
            tags:
                - { name: twig.extension }
    
  4. First Use Case In a Twig template, convert a DateTime object to a human-readable string:
    {{ post.created_at | ago }}
    
    Outputs: "5 minutes ago", "yesterday", etc.

Implementation Patterns

Common Workflows

  1. Date Formatting in Views Use the | ago filter for dynamic, relative time strings:

    <p>Published {{ event.date | ago }}</p>
    
    • Works with DateTime, DateTimeImmutable, or Unix timestamps (as integers).
  2. Customizing Output Extend the bundle’s logic by overriding the Twig extension:

    # app/config/services.yml
    services:
        custom_date_converter:
            class: AppBundle\Twig\CustomDateConverterExtension
            arguments: ["@aga_dateconverter.twig.extension"]
            tags:
                - { name: twig.extension }
    

    Implement Twig_FilterInterface and reuse the original logic.

  3. Integration with Forms Useful for displaying timestamps in form feedback:

    <div class="last-updated">
        Updated {{ record.updated_at | ago }}
    </div>
    
  4. API Responses Serialize dates in JSON responses via Twig (e.g., with JsonResponse):

    return new JsonResponse(['last_active' => $user->lastActive->format('Y-m-d H:i:s')]);
    

    Then render with Twig:

    {{ last_active | ago }}
    

Laravel-Specific Adaptations

Since this is a Symfony2 bundle, adapt it for Laravel by:

  1. Publishing Assets (if needed) Use a Laravel package wrapper (e.g., spatie/laravel-package-tools) to expose config/services.
  2. Service Provider Setup Register the Twig extension in AppServiceProvider:
    public function register()
    {
        $this->app->make('twig')->addExtension(
            new \Aga\DateConverterBundle\Extension\DateConverterTwigExtension()
        );
    }
    
  3. Blade Directives Create a custom Blade directive to mimic the | ago filter:
    Blade::directive('ago', function ($expression) {
        return "<?php echo e(\\Aga\\DateConverterBundle\\Utils::ago($expression)); ?>";
    });
    
    Usage:
    @ago($post->created_at)
    

Gotchas and Tips

Pitfalls

  1. Symfony2 Dependency

    • The bundle targets Symfony2 (not Laravel). Requires manual adaptation for Laravel.
    • Fix: Use a wrapper package or implement the logic directly (see Laravel Carbon for alternatives).
  2. Time Zone Sensitivity

    • The bundle uses the system’s default time zone. Ensure consistency:
      // Symfony2: Set in config.yml
      framework:
          default_locale: "%locale%"
          time_zone: "UTC"
      
      Laravel: Configure in config/app.php:
      'timezone' => 'UTC',
      
  3. Edge Cases

    • Future Dates: The bundle may not handle future dates gracefully (e.g., "in 5 minutes").
    • Workaround: Extend the logic or use a library like Chronology.
  4. Performance

    • The filter runs on every template render. Cache frequent results if used in loops:
      {% set cached_ago = item.created_at | ago %}
      {{ cached_ago }}
      

Debugging

  1. Filter Not Working?

    • Verify the Twig extension is registered:
      php bin/console debug:container aga_dateconverter.twig.extension
      
    • Laravel: Check if the service provider is loaded.
  2. Incorrect Output

    • Inspect the input date format. The bundle expects DateTime objects or Unix timestamps.
    • Debug with:
      {{ dump(item.created_at) }}
      

Extension Points

  1. Custom Rules Override the ago() method in a subclass:

    class CustomDateConverterExtension extends \Aga\DateConverterBundle\Extension\DateConverterTwigExtension
    {
        public function ago($date, $short = false)
        {
            // Custom logic here
            return parent::ago($date, $short);
        }
    }
    
  2. Localization Extend translations by overriding the bundle’s Resources/translations/ files.

  3. Alternative Libraries For Laravel, consider:

    • Carbon: Carbon::createFromFormat(...)->diffForHumans()
    • Moment.js: For frontend rendering.

Pro Tips

  • Combine with Other Filters Chain filters for richer output:
    {{ post.created_at | date('Y-m-d') }} ({{ post.created_at | ago }})
    
  • Use in API Responses Serialize dates as ISO strings and convert client-side with JavaScript (e.g., moment.js).
  • Test Edge Cases Validate with:
    • Past/future dates.
    • Time zones (e.g., DateTime::createFromFormat('Y-m-d H:i:sP', '2023-01-01 12:00:00+0200')).
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui