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条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?