Laravel and Angular Time/Date Display

Posted: 2014-11-10 03:15:30

Angular seems to, by default, easily deal with milliseconds, https://docs.angularjs.org/api/ng/filter/date.

Laravel outputs created_at as a YYYY-MM-DD HH:MM:SS format that just does not work well with the Angular date filter.

It is really simple to change the output of the date in Laravel just add this to your Model or BaseModel or even better Trait

    /**
     * Leave as Timestamps for Angular
     * @return array
     */
    public function getDates()
    {
        return [];
    }

    public function getCreatedAtAttribute($value)
    {
        $value = date('U', strtotime($value));
        return $value * 1000;
    }

    public function getUpdatedAtAttribute($value)
    {
        $value = date('U', strtotime($value));
        return $value * 1000;
    }

This is noted in the docs as well http://laravel.com/docs/4.2/eloquent#date-mutators and http://laravel.com/docs/4.2/eloquent#accessors-and-mutators

Then in Angular I can easily format the date

<small>Created: {{ project.created_at | date:'yyyy-MM-dd' }}</small>

Tags:

laravel php