在Laravel中将默认数据库DateFormat设置为具有时区的ISO 8601 [英] Set default database DateFormat to ISO 8601 with timezones in Laravel

查看:664
本文介绍了在Laravel中将默认数据库DateFormat设置为具有时区的ISO 8601的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I think the title says it: I want to use ISO 8601 with timezones as default DateTime-Format in Laravels Eloquent. I got this

class mEloquent extends Eloquent {

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

}

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

All my models will extend mEloquent. But how should I build the tables? Just

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

正常吗? 如何比较此日期格式?还是应该只使用默认值并分别保存时区?

as normal? How can I compare this dateformat? Or shoud I just use the default one and save the timezone separately?

推荐答案

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

It’s really easy if you follow the documents.

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

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模型将日期属性转换为Carbon对象. Carbon扩展了DateTime,它具有支持所有date格式字符的format功能.

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

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

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.

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

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;

这篇关于在Laravel中将默认数据库DateFormat设置为具有时区的ISO 8601的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆