doufu5521 2015-12-14 10:22
浏览 120
已采纳

比较PHP中的日期时的奇怪问题

I am experiencing an issue when comparing two dates in php.

The problem: When comparing 12:00 AM (midnight) to eg 10:00 AM (morning) the following code will not work properly. According to human logic 10:00 AM is later than 12:00 AM. But computers seem not to recognize that.

Is there any way to do this differently?

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
}
  • 写回答

3条回答 默认 最新

  • drny20290570 2015-12-14 11:36
    关注

    Because date() return String.

    From the 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.


    Basically, what your code trying to do is something like this:

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

    So, PHP will ignore the "AM" or "PM" string, and just compare the numeric value.

    EDIT: From comparison operator manual:

    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.

    So, because PHP convert their value again, then your code is comparing a different value entirely.


    Is there any way to do this differently?

    Just compare from the strtotime value.

    $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
    }
    

    and later format your value again using date to AM/PM format (if needed).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码