我需要使用PHP比较两个给定的日期,但是根据我的代码,它给出了错误的结果。我在下面解释我的代码。
$date=strtotime('18-05-2019 02:36 PM');
$stdate=date('d-m-Y H:i A',strtotime('18-05-2019'));
if($date==$stdate){
echo 'same date';
}else{
echo 'other date';
}
这里一个日期有date and time
,而另一个日期只有日期格式。我需要使用PHP比较两个日期。按照上面的代码,我得到的结果Other date
是错误的。
答案 0 :(得分:1)
日期字符串“ 18-05-2019”等效于“ 18-05-2019 00:00 AM”。如果没有时间,通常将其设置为午夜。使用strtotime()时要考虑小时和分钟。因此,您的代码实际上可以正确执行。
答案 1 :(得分:1)
在比较值之前,先用date()
设置日期格式。您可以采用strtotime()
生成的UNIX时间戳,并去除时间部分:
$date=date( "Y-m-d", strtotime('18-05-2019 02:36 PM'));
$stdate=date( "Y-m-d", strtotime('18-05-2019'));
if($date==$stdate){
echo 'same date';
}else{
echo 'other date';
}
这已经过测试,并且会回显“相同日期”。