joshbrw / laravel-contextual-dates
Contextual date functionality in Laravel.
Installs: 2 918
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/joshbrw/laravel-contextual-dates
Requires
- php: >=5.6
- illuminate/support: ^5.4
- nesbot/carbon: ^1.22
README
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')