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 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥15 this signal is connected to multiple drivers怎么解决
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus