Laravel의 시간대를 사용하여 기본 데이터베이스 DateFormat을 ISO 8601로 설정

StackOverflow https://stackoverflow.com//questions/25023790

문제

제목이 다음과 같다고 생각합니다.Laravels Eloquent에서 기본 DateTime-Format으로 시간대와 함께 ISO 8601을 사용하고 싶습니다.알 겠어

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

평소대로?이 날짜 형식을 어떻게 비교할 수 있나요?아니면 기본 시간대를 사용하고 시간대를 별도로 저장해야 합니까?

도움이 되었습니까?

해결책

문서대로 따라하시면 ​​정말 쉽습니다.

PHP date 기능 지원 ISO 8601 PHP5부터 우리는 다음을 전달하여 얻을 수 있습니다. 'c' 형식 문자.

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

Laravel 모델은 날짜 속성을 다음으로 변환합니다. Carbon 사물.탄소가 늘어나다 DateTime 이는 format 모든 기능을 지원하는 기능 date 형식 문자.

접근자(또는 새로운 사용자 정의 속성)를 쉽게 생성하여 날짜 속성을 변경할 수 있습니다.그런 다음 탄소를 사용하십시오. 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;

다른 팁

문서에서 언급 한 바와 같이 기본 클래스 '멜로 켄트'

에 이것을 추가하십시오.
/**
 * 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