PHP date_sub. can't substract today and date

后端 未结 1 352
萌比男神i
萌比男神i 2021-01-27 07:34

I am trying to output number of days between today and the date I enter so I have a problem I encounter error: \"Warning: date_diff() expects parameter 2 to be DateTimeInterface

1条回答
  •  -上瘾入骨i
    2021-01-27 07:45

    Your problem lies in that when using date_diff you have to make sure that you're comparing objects that are actual date objects. Also the return type for date_diff is a DateInterval object. You're treating it as a string.

    $today = new DateTime(); // $today is a DateTime object
    $date = new DateTime("2016-09-16"); // $date is also a DateTime object!
    $diff =  date_diff($date,$today); // compare two objects of the same type FTW!
    
    echo $diff->days; // $diff is a DateInterval object, so echo it's 'days' property.
    
    // output: 3 (as of this writing)
    

    Further reading:
    http://php.net/manual/en/class.dateinterval.php
    http://php.net/manual/en/class.datetime.php
    http://php.net/manual/en/function.date-diff.php

    0 讨论(0)
提交回复
热议问题