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
輸出
當您運行代碼時,您將看到以下輸出: