artur-gajewski/date-converter-bundle
composer require artur-gajewski/date-converter-bundle:1.0.*@dev
app/AppKernel.php:
new Aga\DateConverterBundle\DateConverterBundle(),
app/config/services.yml:
services:
aga_dateconverter.twig.extension:
class: Aga\DateConverterBundle\Extension\DateConverterTwigExtension
tags:
- { name: twig.extension }
DateTime object to a human-readable string:
{{ post.created_at | ago }}
Outputs: "5 minutes ago", "yesterday", etc.Date Formatting in Views
Use the | ago filter for dynamic, relative time strings:
<p>Published {{ event.date | ago }}</p>
DateTime, DateTimeImmutable, or Unix timestamps (as integers).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.
Integration with Forms Useful for displaying timestamps in form feedback:
<div class="last-updated">
Updated {{ record.updated_at | ago }}
</div>
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 }}
Since this is a Symfony2 bundle, adapt it for Laravel by:
spatie/laravel-package-tools) to expose config/services.AppServiceProvider:
public function register()
{
$this->app->make('twig')->addExtension(
new \Aga\DateConverterBundle\Extension\DateConverterTwigExtension()
);
}
| ago filter:
Blade::directive('ago', function ($expression) {
return "<?php echo e(\\Aga\\DateConverterBundle\\Utils::ago($expression)); ?>";
});
Usage:
@ago($post->created_at)
Symfony2 Dependency
Time Zone Sensitivity
// Symfony2: Set in config.yml
framework:
default_locale: "%locale%"
time_zone: "UTC"
Laravel: Configure in config/app.php:
'timezone' => 'UTC',
Edge Cases
Performance
{% set cached_ago = item.created_at | ago %}
{{ cached_ago }}
Filter Not Working?
php bin/console debug:container aga_dateconverter.twig.extension
Incorrect Output
DateTime objects or Unix timestamps.{{ dump(item.created_at) }}
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);
}
}
Localization
Extend translations by overriding the bundle’s Resources/translations/ files.
Alternative Libraries For Laravel, consider:
Carbon::createFromFormat(...)->diffForHumans(){{ post.created_at | date('Y-m-d') }} ({{ post.created_at | ago }})
moment.js).DateTime::createFromFormat('Y-m-d H:i:sP', '2023-01-01 12:00:00+0200')).How can I help you explore Laravel packages today?