在Laravel中将默认数据库DateFormat设置为带有时区的ISO 8601

cus*_*sti 5 php mysql iso8601 laravel eloquent

我认为标题是这样的:我想使用带有时区的ISO 8601作为Laravels Eloquent中的默认DateTime-Format.我懂了

class mEloquent extends Eloquent {

   protected function getDateFormat()
   {
       return 'YYYY-MM-DDThh:mm:ss.sTZD';
   }

}
Run Code Online (Sandbox Code Playgroud)

我的所有模型都将扩展mEloquent.但是我应该如何构建表格呢?只是

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateUsersTable extends Migration {

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('users', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('firstName');
        $table->string('lastName');
        $table->string('email')->unique();
        $table->string('password');
        $table->timestamps();
    });
} ......
Run Code Online (Sandbox Code Playgroud)

像平常一样?我该如何比较这个日期格式?或者我只是使用默认值并单独保存时区?

小智 6

如文档中所述,将其添加到您的基类“mEloquent”中

/**
 * The storage format of the model's date columns.
 *
 * @var string
 */
protected $dateFormat = 'c';
Run Code Online (Sandbox Code Playgroud)

您还可以查看日期序列化:https : //laravel.com/docs/5.6/eloquent-serialization#date-serialization

  • 这应该是公认的答案,因为它直接回答了问题,而不是假设的问题。 (2认同)

Chr*_*ras 5

如果您遵循这些文档,这真的很容易。

自PHP5起,PHP date函数就支持ISO 8601,我们可以通过传递'c'格式字符来获取它。

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

Laravel模型将日期属性转换为Carbon对象。Carbon扩展DateTime具有format支持所有date格式字符的功能。

您可以轻松创建访问器(甚至是新的自定义属性)来更改日期属性。然后使用Carbon format方法将其更改为ISO 8601格式。

因此,在laravel模型中,我们可以执行以下操作:

public function getPublishedAt8601Attribute()
{
    return $this->published_at->format('c');
}
Run Code Online (Sandbox Code Playgroud)

然后我们可以像这样访问属性:

// Prints something like: 2016-10-13T21:48:00+03:00
echo $post->published_at_8601;
Run Code Online (Sandbox Code Playgroud)


Kvl*_*ctk 5

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

$obj = $this->repository->find($id);
echo $obj->created_at->toW3cString();
Run Code Online (Sandbox Code Playgroud)

输出

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