Framework: Carbon trailing data for dates with timezone

Created on 16 Dec 2016  路  5Comments  路  Source: laravel/framework

  • Laravel Version: 5.3.28
  • PHP Version: 7.0.12
  • Database Driver & Version: pgsql with PostgreSQL 9.6

Description:

If the created_at and updated_at timestamps where created with $table->timestampsTz(); and I run echo \App\User::first()->created_at this exception occurs:

InvalidArgumentException in Carbon.php line 425:
Trailing data in Carbon.php line 425
at Carbon::createFromFormat('Y-m-d H:i:s', '2016-12-16 09:24:04+00') in Model.php line 2999
at Model->asDateTime('2016-12-16 09:24:04+00') in Model.php line 2650
at Model->getAttributeValue('created_at') in Model.php line 2612
at Model->getAttribute('created_at') in Model.php line 3462
at Model->__get('created_at') in web.php line 21

The same is true for relations with pivots that contain the ->withTimestamps() modifier.

Steps To Reproduce:

  1. Use a postgres database
  2. Change default user migration to use ->timestampsTz() instead of ->timestamps()
  3. Insert a user record
  4. Add echo \App\User::first()->created_at; to any controller

Possible Solution:

I'm not very familiar with the internals of Eloquent nor Carbon, but the following patch seems to work (at least the exception is gone):

laravel/framework/src/Illuminate/Database/Eloquent/Model.php
2995a2996,3001
>         // If the value contains some TZ information, we try to properly parse it
>         $dateFormat = $this->getDateFormat();
>         if (!ends_with($dateFormat, 'T') && preg_match('/\+\d{2}:?\d{0,2}$/', $value)) {
>             $dateFormat .= 'T';
>         }
>
2999c3005
<         return Carbon::createFromFormat($this->getDateFormat(), $value);
---
>         return Carbon::createFromFormat($dateFormat, $value);

Most helpful comment

One possible solution in my view would be that you set the $dateFormat property in your Eloquent model to be in the format you want. Suppose:

protected $dateFormat = 'Y-m-d H:i:sO';

But you would need to change your created_at & updated_at fields to string though to make it work.

All 5 comments

One possible solution in my view would be that you set the $dateFormat property in your Eloquent model to be in the format you want. Suppose:

protected $dateFormat = 'Y-m-d H:i:sO';

But you would need to change your created_at & updated_at fields to string though to make it work.

Yes you need to update the default date format of the model, but make sure all date-casted attributes have the same format.

Yes, $dateFormat is a proper solution. But I thought it might be a good thing to fix in Laravel itself, as timestamps with TZ are nothing special.

If you don't plan to support this case out of the box, I'm fine with it. Maybe this is something to note in the documentation of Eloquent?

I have this problem also once a time but I use the date format Y-m-d H:i:sP in each model.

For Me I am I had Created New Trait

<?php


    namespace App\Models\Traits;


    use Carbon\Carbon;
    use Carbon\CarbonInterface;
    use Illuminate\Support\Facades\Date;

    trait PostgresTimestamp
    {
        public function freshTimestamp()
        {
            return Carbon::now();
        }

        protected function asDateTime($value)
        {
            // If this value is already a Carbon instance, we shall just return it as is.
            // This prevents us having to re-instantiate a Carbon instance when we know
            // it already is one, which wouldn't be fulfilled by the DateTime check.
            if($value instanceof CarbonInterface) {
                return Date::instance($value);
            }

            // If the value is already a DateTime instance, we will just skip the rest of
            // these checks since they will be a waste of time, and hinder performance
            // when checking the field. We will just return the DateTime right away.
            if($value instanceof DateTimeInterface) {
                return Date::parse(
                    $value->format('Y-m-d H:i:s.u'), $value->getTimezone()
                );
            }

            // If this value is an integer, we will assume it is a UNIX timestamp's value
            // and format a Carbon object from this timestamp. This allows flexibility
            // when defining your date fields as they might be UNIX timestamps here.
            if(is_numeric($value)) {
                return Date::createFromTimestamp($value);
            }

            // If the value is in simply year, month, day format, we will instantiate the
            // Carbon instances from that format. Again, this provides for simple date
            // fields on the database, while still supporting Carbonized conversion.
            if($this->isStandardDateFormat($value)) {
                return Date::instance(\Illuminate\Support\Carbon::createFromFormat('Y-m-d', $value)->startOfDay());
            }

            $format = $this->getDateFormat();

//          dd($format);
            // https://bugs.php.net/bug.php?id=75577
            if(version_compare(PHP_VERSION, '7.3.0-dev', '<')) {
                $format = str_replace('.v', '.u', $format);
            }

            // Finally, we will just assume this date is in the format used by default on
            // the database connection and use that format to create the Carbon object
            // that is returned back out to the developers after we convert it here.
            return Carbon::parse($value)->toDateTime();
        }


    }
Was this page helpful?
0 / 5 - 0 ratings