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

时间:2014-07-29 19:52:47

标签: php mysql laravel eloquent iso8601

我认为标题是这样的:我希望在Laravels Eloquent中使用带有时区的ISO 8601作为默认的DateTime-Format。我得到了这个

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();
    });
} ......

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

5 个答案:

答案 0 :(得分:4)

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

自PHP5以来,

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

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

Laravel模型将日期属性转换为Carbon个对象。 Carbon扩展DateTime,其format函数支持所有date格式字符。

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

所以在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;

答案 1 :(得分:2)

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

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

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

答案 2 :(得分:0)

exp://5c-gp9.[accountname].my-new-project.exp.direct:80

输出

  

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

答案 3 :(得分:0)

最佳解决方案:

$order_date = $order->created_at;
$date_changed=$order_date->toIso8601String();

答案 4 :(得分:0)

在您的Eloquent模型中,将$dateFormat变量设置为DateTime::ISO8601

    protected $dateFormat = DateTime::ISO8601;

其他人提到使用'c'格式,但是我发现这不起作用,因为Laravel在转换不支持DateTime::createFromFormat选项的DateTime时使用了'c'函数。

相关问题