请帮我解释我的代码有什么问题.它总是显示今天大于2016年2月1日?2016年的地方大于2015年.
<?php
$date_now = date("m/d/Y");
$date=date_create("01/02/2016");
$date_convert = date_format($date,"m/d/Y");
if ($date_now > $date_convert) {
echo 'greater than';
}else{
echo 'Less than';
}
Run Code Online (Sandbox Code Playgroud)
PS:01/02/2016来自我的数据库
Joh*_*nde 79
你不是在比较日期.你正在比较字符串.在字符串比较的世界中,09/17/2015> 01/02/2016因为09> 01.您需要以可比较的字符串格式输入日期或比较DateTime可比较的对象.
<?php
$date_now = date("Y-m-d"); // this format is string comparable
if ($date_now > '2016-01-02') {
echo 'greater than';
}else{
echo 'Less than';
}
Run Code Online (Sandbox Code Playgroud)
要么
<?php
$date_now = new DateTime();
$date2 = new DateTime("01/02/2016");
if ($date_now > $date2) {
echo 'greater than';
}else{
echo 'Less than';
}
Run Code Online (Sandbox Code Playgroud)
Joy*_*yal 12
我们可以将日期转换成时间戳来进行比较
<?php
$date_now = time(); //current timestamp
$date_convert = strtotime('2022-08-01');
if ($date_now > $date_convert) {
echo 'greater than';
} else {
echo 'Less than';
}
?>
Run Code Online (Sandbox Code Playgroud)