dousha7645 2017-03-21 19:14
浏览 205
已采纳

使用DateTime类和modify()方法时日期更改

Im feeling my way around the \DateTime class which is native to PHP but I have found a peculiar habit.

$date = new \DateTime(date('d-m-Y',time())); //this being todays date 21-03-2017

$first = $date->modify('first day of this month');
var_dump($first); //returns ["date"] => string(26) "2017-03-01..."
$last = $date->modify('last day of this month');
var_dump($first); //returns ["date"] => string(26) "2017-03-31..."

It appears to assigned by reference and thus gets modified later. How can I prevent this.

  • 写回答

1条回答 默认 最新

  • doutou3725 2017-03-21 19:18
    关注

    The method DateTime::modify (add and sub also) is to modify the class (don't to create a new own). As you can see on the manual:

    $date = new DateTime('2006-12-12');
    $date->modify('+1 day');
    
    echo $date->format('Y-m-d');//2006-12-13
    

    When you assign the returned date with a new variable, you're assigning only a reference. Wich means that both variables are looking to the same object in memory.

    $date = new DateTime('2006-12-12');
    $nextDay = $date->modify('+1 day');
    
    echo $date->format('Y-m-d');//2006-12-13
    echo $nextDay->format('Y-m-d');//2006-12-13
    

    If you want to change a DateTime without modifying the object (creating a new one) use DateTimeImmutable

    $date = new DateTimeImmutable('2006-12-12');
    $nextDay = $date->modify('+1 day');
    
    echo $date->format('Y-m-d');//2006-12-12
    echo $nextDay->format('Y-m-d');//2006-12-13
    

    Another approach is with clone keyword:

    $first = clone $last = new \DateTime(date('d-m-Y',time())); //this being todays date 21-03-2017
    
    $first->modify('first day of this month');
    var_dump($first);
    
    $last->modify('last day of this month');
    var_dump($last);
    

    Code: https://3v4l.org/rO7Zd Result:

    object(DateTime)#2 (3) {
      ["date"]=>
      string(26) "2017-03-01 00:00:00.000000"
      ["timezone_type"]=>
      int(3)
      ["timezone"]=>
      string(16) "Europe/Amsterdam"
    }
    object(DateTime)#1 (3) {
      ["date"]=>
      string(26) "2017-03-31 00:00:00.000000"
      ["timezone_type"]=>
      int(3)
      ["timezone"]=>
      string(16) "Europe/Amsterdam"
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 arduino控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥85 maple软件,solve求反函数,出现rootof怎么办?
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题