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 esp32驱动GC9A01循环播放视频
  • ¥15 惠普360g9的最新bios
  • ¥15 配置hadoop时start-all.sh老是启动失败
  • ¥30 这个功能用什么软件发合适?
  • ¥60 微信小程序,取消订单,偶尔订单没有改变状态
  • ¥15 用pytorch实现PPO算法
  • ¥15 关于调制信号的星座图?
  • ¥30 前端传参时,后端接收不到参数
  • ¥15 这是有什么问题吗,我检查许可证了但是显示有呢
  • ¥15 机器学习预测遇到的目标函数问题