Set default database DateFormat to ISO 8601 with timezones in Laravel

自古美人都是妖i 提交于 2019-12-05 10:15:34

It’s really easy if you follow the documents.

PHP date function supports ISO 8601 since PHP5 and we can get it by passing the 'c' format character.

http://php.net/manual/en/function.date.php

Laravel model converts date attributes to Carbon objects. Carbon extends DateTime which has the format function that supports all of the date format characters.

You can easily create an accessor (or even a new custom attribute) to change a date attribute. Then use the Carbon format method to change it to ISO 8601 format.

So in a laravel model, we can do something like this:

public function getPublishedAt8601Attribute()
{
    return $this->published_at->format('c');
}

and then we can access the attribute like this:

// Prints something like: 2016-10-13T21:48:00+03:00
echo $post->published_at_8601;

As mentioned in the docs, add this to your base class 'mEloquent'

/**
 * The storage format of the model's date columns.
 *
 * @var string
 */
protected $dateFormat = 'c';

You can also check out date serializations: https://laravel.com/docs/5.6/eloquent-serialization#date-serialization

$date = Carbon::now();
echo $date->toW3cString();

$date = $this->repository->find($id);
echo $date->created_at->toW3cString();

Output

2018-04-14T18:35:58+00:00

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!