CakePHP - Date and Time


To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

To work with date and time, include the class in your controller

use Cake\I18n\FrozenTime;

Let us work, on an example and display date and time, using FrozenTime class.


Make Changes in the config/routes.php file as shown in the following program.


use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->scope('/', function (RouteBuilder $builder) {
   $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
      'httpOnly' => true,
   //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']);

Create a DatesController.php file at src/Controller/DatesController.php. Copy the following code in the controller file. Ignore if already created.


   namespace App\Controller;
   use App\Controller\AppController;
   use Cake\I18n\FrozenTime;
   class DatesController extends AppController{
      public function index(){
         $time = FrozenTime::now();
         $now = FrozenTime::parse('now');
         $_now = $now->i18nFormat('yyyy-MM-dd HH:mm:ss');
         $this->set('timenow', $_now);
         $now = FrozenTime::parse('now');
         $nice = $now->nice();
         $this->set('nicetime', $nice);
         $hebrewdate = $now->i18nFormat(\IntlDateFormatter::FULL, null, 'en-IR@calendar=hebrew');
         $japanesedate = $now->i18nFormat(\IntlDateFormatter::FULL, null, 'en-IR@calendar=japanese');
         $time = FrozenTime::now();

Create a directory Dates at src/Template and under that directory create a View file called index.php. Copy the following code in that file.


   echo "The Current date and time is = ".$timenow;
   echo "<br/>";
   echo "Using nice format available = ".$nicetime;
   echo "<br/>";
   echo "Date and Time as per Hebrew Calender =" .$hebrewdate;
   echo "<br/>";
   echo "Date and Time as per Japanese Calender =" .$japanesedate;
   echo "<br/>";
   echo "Current Year = ".$current_year;
   echo "<br/>";
   echo "Current Month = ".$current_month;
   echo "<br/>";
   echo "Current Day = ".$current_day;

Execute the above example by visiting the following URL −



When you run the code, you will see the following output −

Current Date