CakePHP 日期和时间

cakephp 日期和时间

 

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

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

use cake\i18n\frozentime;

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

 

示例

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

 

config/routes.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

   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

   echo "the current date and time is = ".$timenow;
   echo "
";
   echo "using nice format available = ".$nicetime;
   echo "
";
   echo "date and time as per hebrew calender =" .$hebrewdate;
   echo "
";
   echo "date and time as per japanese calender =" .$japanesedate;
   echo "
";
   echo "current year = ".$current_year;
   echo "
";
   echo "current month = ".$current_month;
   echo "
";
   echo "current day = ".$current_day;
?>

通过访问以下 url 执行上述示例:

http://localhost/cakephp4/datetime

 

输出

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

下一节:cakephp 文件上传

cakephp 教程

相关文章