dpjw67160 2017-07-31 22:40
浏览 166
已采纳

日期时间的PHP setDate函数设置不同的日期

I am learning to use PHP DateTime class and I came across the handy 'setDate' method. I tried to do the following to compare 2 dates:

$date = new DateTime();
$newDate = clone $date;
$newDate->setDate(2017, 08, 29);

if($date > $newDate){
    echo 'yes';

} else{
    echo "no";
}

According to the current date it shall return 'no' but it returned 'yes'. so I did a var_dump($newDate); and it returned:

object(DateTime)[2]
  public 'date' => string '2016-12-29 00:31:02.000000' (length=26)
  public 'timezone_type' => int 3
  public 'timezone' => string 'Europe/Zurich' (length=13)

It returned 2016-12-29 as the date which is not what I intended to set.

surely there something really wrong with what I am doing. Please help me find my mistake. Thanks

  • 写回答

2条回答 默认 最新

  • douou2026 2017-07-31 22:53
    关注

    Instead of 08, it need to be 8 like below:-

    <?php
    
    $date = new DateTime();
    $newDate = clone $date;
    $newDate->setDate(2017, 8, 29);
    
    if($date > $newDate){
        echo 'yes';
    
    } else{
        echo "no";
    }
    

    Output:-https://eval.in/839909

    Why:- As @Mark Baker tell correctly:-

    Numbers prefixed with 0 in PHP are treated as octal, so 08 is octal 8, which is an invalid octal number, so treated as 0

    And because of it you get yes as output:- https://eval.in/839910

    You can check a number is octal or not like below:-

    <?php
    
    function is_octal($x) {
        return decoct(octdec($x)) == $x;
    }
    
    echo is_octal(08); // true
    

    Output:- https://eval.in/839915 (the above code will work in php<7)

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

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划