我if...else在 PHP 中使用日期在操作中存在邏輯問題。
我想要的是:
- 如果
$jd小于$jam列印輸出“紅色” - 如果介于
$jam和$jam加上 2 小時列印輸出“綠色”, - 如果
$jd超過$h1列印輸出“白色”。
這是源代碼:
date_default_timezone_set('Asia/Jakarta');
$jam = Date('H:i');
$jd = '12:00:00';
$h1 = $jd 2;
if ($jd > $h1){
echo 'white';
} elseif ($jd < $h1) {
if ($jd > $jam) {
echo 'green';
} else {
echo 'red';
}
}
問題是$jd超過$jam2 小時的值是列印輸出“綠色”而不是“白色”。
它似乎不適用于日期操作,但使用數字它可以作業。
uj5u.com熱心網友回復:
當您的比較涉及日期時,您應該使用 DateTime 物件。您正在處理日期和時間,因為它們是字串并直接比較它們。
這是一個盡可能接近您的代碼的示例,以展示您應該如何創建物件DateTime以及DateInterval如何相互比較和使用它們。
該演示使用:
- https://www.php.net/manual/en/datetime.add.php
- https://www.php.net/manual/en/datetime.createfromformat.php
- https://www.php.net/manual/en/datetimeimmutable.construct
- https://www.php.net/manual/en/dateinterval.createfromdatestring
<?php
//$jam holds the now datetime(Immutable) (as object.. not as string!)
$jam = new DateTimeImmutable();
//jd holds a a datetime containing now (where the time part is 12:00:00 as specified in hh:mm:ss format)
$jd = DateTime::createFromFormat('H:i:s', '12:00:00');
//puts in $h1: $jam 2hours (that's why we used DateTimeImmutable instead of DateTime
//otherwise the add method would have altered directly the calling object $jam)
$h1 = $jam->add( DateInterval::createFromDateString('2 hours') );
//this is an example on how to convert those datetime to string and print to screen
echo $jam->format('H:i');
echo $h1->format('D M j, Y G:i:s T');
//here you are doing comparisons between full datetimes (including the date parts)
if ($jd > $h1){
echo 'white';
} else if ($jd < $h1) {
if ($jd > $jam) {
echo 'green';
} else {
echo 'red';
}
}
uj5u.com熱心網友回復:
基本上最好使用 DateTime。DateTime 物件可以直接比較,因此可以省略格式化。
date_default_timezone_set('Asia/Jakarta');
$staticTime = '12:00:00';
$dt = date_create($staticTime);
$now = date_create('now');
$color = 'green';
if($dt < $now) {
$color = 'red';
}
elseif($dt > date_create('now 2 hours')) {
$color = 'white';
}
echo 'At '.$now->format('H:i').' Color='.$color;
new DateTime() 或date_create()也可以直接理解許多運算式,例如“now 2 hours”。
在https://3v4l.org/bebSt上自行嘗試
uj5u.com熱心網友回復:
date_default_timezone_set('Asia/Jakarta');
$staticTime = '12:00:00';
$jam = strtotime(date('H:i'));
$jd = strtotime($staticTime);
$h1 = strtotime($jam . " 2hours");
if($jd < $jam) {
echo 'red';
} else if($jd > $jam && $jd < $h1 ) {
echo 'green';
} else if($jd > $h1) {
echo 'white';
}
將時間轉換為 strtotime 進行比較
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/464721.html
