比较 php 中的日期时出现奇怪的问题

Weird issue when comparing dates in php

我在比较 php 中的两个日期时遇到问题。

问题: 将 12:00 AM(午夜)与 10:00 AM(早晨)进行比较时,以下代码将无法正常工作。根据人类逻辑 10:00 AM 晚于 12:00 AM。但计算机似乎无法识别。

有什么不同的方法吗?

date_default_timezone_set('Europe/Athens');
$today = date("d-m-Y h:i:s A");
$today = date("d-m-Y h:i:s A",strtotime($today));
$max = date('d-m-Y h:i:s A', strtotime("31-12-2015 23:59:00"));
$min = date('d-m-Y h:i:s A', strtotime("14-12-2015 00:00:01"));

if (($today > $min) && ($today < $max)){
    //do something
} else {
    //something else done
}

这样试试..

date_default_timezone_set('Europe/Athens');
            $today = date("d-m-Y h:i:s A");                
            $max = date('d-m-Y h:i:s A', strtotime("31-12-2015 23:59:00"));
            $min = date('d-m-Y h:i:s A', strtotime("14-12-2015 00:00:01"));

            if ((strtotime($today) > strtotime($min)) && (strtotime($today) < strtotime($max))){
                    //do something

            }else{
                    //something else done

例如:

if (strtotime("12:00 AM")>strtotime("10:00 AM")){
 echo "do something";
}else{
 echo "something else done"; 
}

//输出"something else done";

您可以使用 date_create() & date_diff() PHP 内置函数来比较两个日期,在您的场景中它会帮助您。

$date1 = date_create("2013-03-15"); 
$date2 = date_create("2013-12-12");
$diff = date_diff($date1,$date2);
echo $diff->format("%R%a days");

因为date() return字符串.

来自manual

Return Values

Returns a formatted date string. If a non-numeric value is used for timestamp, FALSE is returned and an E_WARNING level error is emitted.


基本上,您的代码试图做的是这样的:

if("31-12-2015 23:59:00 PM" < "14-12-2015 00:00:01 AM") {
    .......
}

所以,PHP会忽略"AM"或"PM"字符串,只比较数值。

编辑:来自comparison operator手册:

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.

因此,因为 PHP 再次转换它们的值,所以您的代码正在比较一个完全不同的值。


Is there any way to do this differently?

只需从 strtotime 值进行比较。

$today = strtotime("now");
$max = strtotime("31-12-2015 23:59:00");
$min = strtotime("14-12-2015 00:00:01");

if (($today > $min) && ($today < $max)){
        //do something

}else{
        //something else done
}

然后使用 date 格式再次格式化您的值到 AM/PM 格式(如果需要)。