CakePHP 日期和时间

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

要处理日期和时间,请在控制器中包含该类

use Cake\I18n\FrozenTime;

让我们使用 FrozenTime 类来处理示例并显示日期和时间。

示例

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

config/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 的 View 文件。将以下代码复制到该文件中。

src/Template/Dates/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

输出

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

当前日期

下一章:CakePHP 文件上传

  为了处理文件上传,我们将使用表单助手。这是一个文件上传示例。  示例 在config/routes.php文件中进行修改,如下程序所示。  config/routes.php & ...