Date conversions

Hi everyone,

I save my dates in the format datetime in mysql.
I just want to format them for display resons.

I found 2 ways. Both work. Is there a difference or a preferred one?

<td><?= h($ticket->created->i18nFormat('dd.MM.yyyy')) ?></td>
<td><?= h($ticket->created->format('d.m.Y')) ?></td>

Thank you!

:pray:

both are fine, just one uses PHP’s default date format strings and the other uses the ICN format strings.

1 Like

Perfect, and thank you for the quick reply. :+1:

If you want to apply it everywhere in the cake app, you could do this in your AppController:

<?php
namespace App\Controller;
use Cake\Controller\Controller;
use Cake\I18n\FrozenDate;
use Cake\I18n\FrozenTime;

class AppController extends Controller {
  public function initialize(): void {
    parent::initialize();

    // set date and time format
    FrozenDate::setToStringFormat('dd.MM.yyyy');
    FrozenTime::setToStringFormat('dd.MM.yyyy, HH:mm');

    // load components
    $this->loadComponent('Flash');
    // ..
  }

 ...
}

Then you do not need to do this eveytime:

<td><?= h($ticket->created->format('d.m.Y')) ?></td>

You can just do this:

<td><?= h($ticket->created) ?></td>

AppController is only used in web requests, not CLI commands.

Its recommended to put these kind of setToStringFormat() calls into the config/bootstrap.php since its actually used everywhere.

2 Likes

The CLI is a good point @KevinPfeifer, thank you for the hint.
I tried to define this settings in the bootstrap and saw, that some things with Date and Time have changed in version 5.
So to define it in the bootstrap.php, the following is needed:

// set date and time format
Cake\I18n\Date::setToStringFormat('dd.MM.yyyy');
Cake\I18n\DateTime::setToStringFormat('dd.MM.yyyy HH:mm');

Inside templating i prefer to use the helpers which wrap the logic with better syntactic sugar

1 Like