我在PHP中使用日期操作if...else
有逻辑问题。
我要的是:
- 如果
$jd
小于$jam
打印'红色' - 如果在
$jam
和$jam
之间加上2小时打印'绿色', - 如果
$jd
大于$h1
,则输出'white'.
源代码:
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
值超过$jam
加上2小时,它打印出'绿色'而不是'白色'。
似乎不能用日期运算,但可以用数字运算。
当您的比较涉及日期时,您应该使用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';
}
}
基本上最好使用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上试一下
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以比较