joshbrw/laravel-contextual-dates
Laravel Contextual Dates
Installation
- Install the package via Composer:
composer require joshbrw/laravel-contextual-dates - Add the Service Provider to
config/app.php:Joshbrw\LaravelContextualDates\ContextualDatesServiceProvider::class - Configure the
DateTimeFactorywith the desired Timezone and Formats. These formats can be named whatever you like, i.e.longorshort. - Use the
FormatsDatestrait or the helpers defined inhelpers.phpto localize/output the dates.
Defaults
Two date formats are provided by default, long and short. These can be over-ridden at any time.
Examples
Using Container
The DateTimeFactory is bound as a singleton in the container, so it can be picked up and modified at any time (similar to the inbuilt View/Validation factories that Laravel provides).
$dateTimeFactory = app(DateTimeFactory::class);
$dateTimeFactory->addFormat('mixed', 'Y-m-d');
$carbon = new \Carbon\Carbon;
$dateTime = $dateTimeFactory->createFromCarbon($carbon);
echo $dateTime->format('mixed'); /* Outputs in Y-m-d */
Using Helpers
This package ships with two helper methods; localize_date() and format_date().
$dateTimeFactory = app(DateTimeFactory::class);
$dateTimeFactory->addFormat('mixed', 'Y-m-d');
$carbon = new \Carbon\Carbon;
$instance = localize_date($carbon); /* Instance of DateTime */
echo format_date($carbon, 'mixed'); /* Outputs in Y-m-d */
Using Blade Directive
You can format dates in the Views using the Blade Directive. All this does is proxy to the format_date() helper method.
@date(new Carbon, 'long')