CakePHP - Tanggal dan Waktu
Untuk bekerja dengan tanggal dan waktu di cakephp4, kita akan menggunakan kelas FrozenTime yang tersedia.
Untuk bekerja dengan tanggal dan waktu, sertakan kelas dalam pengontrol Anda
use Cake\I18n\FrozenTime;
Mari kita bekerja, pada contoh dan menampilkan tanggal dan waktu, menggunakan kelas FrozenTime.
Contoh
Lakukan perubahan pada file config / routes.php seperti yang ditunjukkan pada program berikut.
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();
});
Membuat DatesController.php mengajukan di src/Controller/DatesController.php.Salin kode berikut di file pengontrol. Abaikan jika sudah dibuat.
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);
}
}
?>
Buat direktori Dates di src/Template dan di bawah direktori itu buat a Viewfile bernama index.php. Salin kode berikut di file itu.
src / Template / Tanggal / 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;
?>
Jalankan contoh di atas dengan mengunjungi URL berikut -
http: // localhost / cakephp4 / datetime
Keluaran
Saat Anda menjalankan kode, Anda akan melihat output berikut -