我想标题说明了这一点:我想在Laravels Eloquent中使用带有时区的ISO8601作为默认日期时间格式。我得到了这个

class mEloquent extends Eloquent {

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

}

我所有的模型都将扩展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();
    });
} ......

正常吗?我怎样才能比较这个dateformat?或者我只是使用默认的,并单独保存时区?

有帮助吗?

解决方案

如果你遵循这些文件,这真的很容易。

PHP的 date 功能支持 ISO8601 从PHP5开始,我们可以通过 'c' 格式字符。

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

Laravel模型将日期属性转换为 Carbon 物体。碳延伸 DateTime 其中有 format 功能,支持所有的 date 格式化字符。

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

所以在laravel模型中,我们可以做这样的事情:

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

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

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

其他提示

如文档中所述,将此添加到您的基类'Meloquent'

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

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

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

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

输出

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top