Formatting Timestamps in Laravel

  • February 11, 2015

Welcome to the incredibly popular Easy Laravel 5 companion blog. To celebrate the new edition's release (updated for Laravel 5.5!) use the discount code easteregg to receive 20% off the book or book/video package! » Buy the book

Laravel will automatically create two timestamp columns when generating a new database table via a migration:

Schema::create('tasks', function(Blueprint $table)
{
  ...
  $table->timestamps();
});

The call to $table->timestamps() will result in two columns of type timestamp being added to the table, including created_at and updated_at. These fields will automatically be updated when a new record is created and updated, respectively. It's occasionally useful to output these dates and/or times to your view when presenting information about a particular record, however the default format looks like 2015-02-11 08:12:49 which isn't particularly user friendly.

You can however modify this format to a more user friendly version using PHP's date() and strtotime() functions, as demonstrated by the below example:

{% raw %}
<p>
Created on: {{ date('F d, Y', strtotime($list->created_at)) }} <br />
Last modified: {{ date('F d, Y', strtotime($list->updated_at)) }}<br />
{{ $list->description }}
</p>
{% endraw %}

When rendered to the browser, the created_at and updated_at timestamps will look like this:

Created on: February 10, 2015
Last modified: February 11, 2015

Even after 17 years of using PHP's date() function I can't seem to remember the myriad options, so be sure to check out its manual page for a complete list of what's possible.