CakePHP - 日期和时间


为了在 cakephp4 中处理日期和时间,我们将使用可用的 FrozenTime 类。

要使用日期和时间,请将类包含在控制器中

use Cake\I18n\FrozenTime;

让我们使用 FrozenTime 类来研究一个示例并显示日期和时间。

例子

在 config/routes.php 文件中进行更改,如以下程序所示。

配置/routes.php

<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
   $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
      'httpOnly' => true,
   ]));
   $builder->applyMiddleware('csrf');
   //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']);
   $builder->connect('datetime',['controller'=>'Dates','action'=>'index']);
   $builder->fallbacks();
});

在src/Controller/DatesController.php创建DatesController.php文件将以下代码复制到控制器文件中。如果已经创建则忽略。

src/Controller/DatesController.php

<?php
   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');
         $this->set("hebrewdate",$hebrewdate);
         $japanesedate = $now->i18nFormat(\IntlDateFormatter::FULL, null, 'en-IR@calendar=japanese');
         $this->set("japanesedate",$japanesedate);
         $time = FrozenTime::now();
         $this->set("current_year",$time->year);
         $this->set("current_month",$time->month);
         $this->set("current_day",$time->day);
      }
   }
?>

src/Template处创建一个Dates目录,并在该目录下创建一个名为 index.php 的视图文件。将以下代码复制到该文件中。

src/模板/日期/index.php

<?php
   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;
?>

通过访问以下 URL 来执行上述示例 -

http://localhost/cakephp4/datetime

输出

当您运行代码时,您将看到以下输出 -

当前日期