dpjw67160 2017-07-31 14: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 14: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 加热反应炉PLC控制系统设计(相关搜索:梯形图)
  • ¥15 python 用Dorc包报错,我的写法和网上教的是一样的但是它显示无效参数,是什么问题
  • ¥15 指定IP电脑的访问设置
  • ¥30 matlab ode45 未发现警告,但是运行出错
  • ¥15 vscode platformio
  • ¥15 代写uni代码,app唤醒
  • ¥15 全志t113i启动qt应用程序提示internal error
  • ¥15 ensp可以看看嘛.
  • ¥80 51单片机C语言代码解决单片机为AT89C52是清翔单片机
  • ¥60 优博讯DT50高通安卓11系统刷完机自动进去fastboot模式
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部