Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default database DateFormat to ISO 8601 with timezones in Laravel

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?

like image 711
custi Avatar asked Jul 29 '14 19:07

custi


1 Answers

It’s really easy if you follow the documents.

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 model converts date attributes to Carbon objects. Carbon extends DateTime which has the format function that supports all of the date format characters.

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.

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;
like image 149
Christos Lytras Avatar answered Sep 22 '22 11:09

Christos Lytras