Looking to hire Laravel developers? Try LaraJobs

laravel-cast-datetime-tz maintained by codewiser

Description
Cast datetime with timezone for Laravel
Author
Last update
2025/02/28 09:41 (dev-main)
License
Links
Downloads
725

Comments
comments powered by Disqus

Cast datetime with timezone for Laravel

PHP Composer

Laravel doesn't respect timezone. Cast \Codewiser\Casts\AsDatetimeWithTZ fixes this wrong behaviour.

Before

class Article extends \Illuminate\Database\Eloquent\Model
{
    protected $casts = [
        'date' => 'datetime'
    ];
}
// e.g. Laravel has Europe/London (+01:00) timezone
config()->set('app.timezone', 'Europe/London');

$model = new Article();

$model->date = '2000-01-01T10:00:00+02:00';

echo $model->date->format('c');
// Expecting 2000-01-01T09:00:00+01:00
// Actual    2000-01-01T10:00:00+01:00

After

class Article extends \Illuminate\Database\Eloquent\Model
{
    protected $casts = [
        'date' => \Codewiser\Casts\AsDatetimeWithTZ::class
    ];
}
// e.g. Laravel has Europe/London (+01:00) timezone
config()->set('app.timezone', 'Europe/London');

$model = new Article();

$model->date = '2000-01-01T10:00:00+02:00';

echo $model->date->format('c');
// Expecting 2000-01-01T09:00:00+01:00
// Actual    2000-01-01T09:00:00+01:00