為了在 cakephp4 中處理日期和時間,我們將使用可用的 FrozenTime 類別。
要使用日期和時間,請將類別包含在控制器中
use Cake\I18n\FrozenTime;
讓我們使用 FrozenTime 類別來研究範例並顯示日期和時間。
在 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 檔案。 將以下程式碼複製到控制器檔案中。如果已創建,請忽略。
<?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檔案。將以下程式碼複製到該文件中。
<?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 日期和時間的詳細內容。更多資訊請關注PHP中文網其他相關文章!