0

There are many questions that were asked on date_diff PHP function. But mine seems a bit different as I get a rather unusual result. Below is the code I have:

$today = date( 'd-m-Y', strtotime( "now" ) );
$selectDay = date( 'd-m-Y', strtotime( $row->BOOKING_DATE ));
$interval = date_diff( $selectDay, $today );

And the result I get:

Warning: date_diff() expects parameter 1 to be DateTime, string given in...

As you see $today and $selectDay both are dates. Any suggestions? Note: I have PHP version 5.3

John Conde
  • 217,595
  • 99
  • 455
  • 496
sri
  • 338
  • 2
  • 13

3 Answers3

5

The error message is clear. date_diff() expects DateTime() objects but you are passing it strings.

$today     = new DateTime();
$selectDay = new DateTime($row->BOOKING_DATE);
$interval  = date_diff( $selectDay, $today );

Or:

$today     = new date_create();
$selectDay = new date_create($row->BOOKING_DATE);
$interval  = date_diff( $selectDay, $today );

Or:

$today     = new DateTime();
$selectDay = new DateTime($row->BOOKING_DATE);
$interval  = $today->diff( $selectDay );
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • You are missing a `;` for $today? – sri Aug 07 '14 at 12:57
  • 1
    @sri Ooops. Correct. Fixed for all three examples. Thank you for pointing that out. – John Conde Aug 07 '14 at 12:58
  • On echoing $interval I get ` Catchable fatal error: Object of class DateTime could not be converted to string in... `. Any idea? – sri Aug 07 '14 at 13:16
  • 2
    Try using `var_dump()` instead of `echo`. It is an object and not a string. But if you want it formatted you need to use [`DateInterval::format()`](http://php.net/manual/en/dateinterval.format.php) – John Conde Aug 07 '14 at 13:18
3

date returns a textual representation of a UNIX timestamp in the form of a string.

date_diff expects a DateTime object, as documented here:

http://php.net/manual/en/class.datetime.php

Incidentally,

date( 'd-m-Y', strtotime( "now" ) )

is equivalent to date('d-m-Y').

Will Vousden
  • 32,488
  • 9
  • 84
  • 95
0

use date_create() function before passing in date_diff() function params

$today = date( 'd-m-Y', strtotime( "now" ) );
$selectDay = date( 'd-m-Y', strtotime( $row->BOOKING_DATE ));
$interval = date_diff( date_create($selectDay), date_create($today) );
Girish
  • 11,907
  • 3
  • 34
  • 51