在这里我使用一个日期时间对象是这个
$cdate = date('d/m/Y h:i:sa')
另一个日期时间对象是这个
$udate = date("d/m/Y h:i:sa", strtotime("72 hours"));
为了比较我正在使用这个条件
if($cdate >= $udate)
但问题是......在这种情况下,它只比较一天而不是整个日期和时间。
在这里我使用一个日期时间对象是这个
$cdate = date('d/m/Y h:i:sa')
另一个日期时间对象是这个
$udate = date("d/m/Y h:i:sa", strtotime("72 hours"));
为了比较我正在使用这个条件
if($cdate >= $udate)
但问题是......在这种情况下,它只比较一天而不是整个日期和时间。
从返回的字符串date()
仅在某些情况下具有可比性。您应该使用DateTime()
谁的对象总是可比较的:
$cdate = new DateTime();
$udate = new DateTime('+3 days');
if($cdate >= $udate) {
}
if(strtotime($cdate) >= strtotime($udate)){
// your condition
}
希望能帮助到你 :)
该date()
函数返回一个字符串 - 而不是 DateTime 对象。因此,>=
您正在进行的比较是字符串比较,而不是日期/时间的比较。
如果您真的想进行字符串比较,请使用这种排序有意义的格式,例如 ISO 8601。您可以使用格式“c”轻松完成此操作。
然而,更好的是比较实际的 DateTime 对象或整数 timstamps(例如你会得到什么time()
)。
您的代码比较日期错误,因为日期返回字符串。
试试这个:
$cdate = new DateTime();
$udate = new DateTime('72 hours');
if($udate > $cdate) {
echo 'something';
}
您不比较日期时间,并且OOP
您的代码中没有对象(如 in )。$cdate
并且$udate
是字符串,这就是使用字符串比较规则(即字典顺序)比较它们的原因。
您可以使用时间戳(只是整数秒):
// Use timestamps for comparison and storage
$ctime = time();
$utime = strtotime("72 hours");
// Format them to strings for display
$cdate = date('d/m/Y h:i:sa', $ctime);
$udate = date('d/m/Y h:i:sa', $utime);
// Compare timestamps
if ($ctime < $utime) {
// Display strings
echo("Date '$cdate' is before date '$udate'.\n");
}
或者您可以使用以下类型的对象DateTime
:
$cdate = new DateTime('now');
$udate = new DateTime('72 hours');
// You can compare them directly
if ($cdate < $udate) {
// And you can ask them to format nicely for display
echo("Date '".$cdate->format('d/m/Y h:i:sa')."' is before date '".
$udate->format('d/m/Y h:i:sa')."'\n");
}