Thursday, December 3, 2015

Displaying Dates in CakePHP Templates

I didn't find it exactly intuitive in the documentation, so I thought I'd post up a short 'n' sweet about how to format dates and times in CakePHP templates.

Cake\I18n\Time::i18nFormat with IntlDateFormatter provides some easy options.  For example:

<td><?= $this->Time->i18nFormat($employee->birth_date, [\IntlDateFormatter::MEDIUM, \IntlDateFormatter::NONE]) ?></td>

PHP's IntlDateFormatter class contains a number of constants (e.g. NONE, FULL, LONG, MEDIUM, SHORT) that can be used in combination to show variations on the date and time.  In the example above, I used "MEDIUM" for the date and "NONE" for the time to get the result shown below:



Setting both the date and time to "FULL" results in:



You can, of course, format your dates/times manually as well:

<td><?= $this->Time->i18nFormat($employee->hire_date, 'yyyy-MM-dd HH:mm:ss') ?></td>

The above results in:



According to the CakePHP docs on dates and times, "anything you can do with Carbon and DateTime, you can do with (CakePHP's) Time.

No comments:

Post a Comment