0

I am using this code:

//get days
$a = date_create($arrive);
$d = date_create($leave);
//$days = date_diff($d,$a);

echo '<input type="hidden" id="days" value="'.date_diff($d,$a).'"/>';

and getting this error: Catchable fatal error: Object of class DateInterval could not be converted to string

I do not know how to fix the issue.

John Conde
  • 217,595
  • 99
  • 455
  • 496
Burning Hippo
  • 787
  • 1
  • 20
  • 47

1 Answers1

7

date_diff() returns a DateInterval object which you need to call format() on to get the actual value from it. In this case you will use %d to get the number of days.

//get days
$a = date_create($arrive);
$d = date_create($leave);
$diff = date_diff($d,$a);

echo '<input type="hidden" id="days" value="'.$diff->format("%d").'"/>';

Just keep in mind this will only go up to 31. From there you will need to use %m with %d to also display months.

See it in action

John Conde
  • 217,595
  • 99
  • 455
  • 496
  • 4
    You can just use `$diff->days` (or `$diff->d`) :-D – gen_Eric Oct 30 '13 at 20:13
  • @RocketHazmat I *always* forget about that! – John Conde Oct 30 '13 at 20:14
  • The error went away but when I do a log of the hidden input it says undefined. – Burning Hippo Oct 30 '13 at 20:15
  • Can you provide us with valid values for `$arrive` and `$leave` so we cna do better testing? – John Conde Oct 30 '13 at 20:18
  • `$arrive = '2013-10-01'; $leave = '2013-10-11';` That what you mean? I even made the input a textbox to make sure the number got there and it did. I am using this to acces it: `var days = $('#days').val();` – Burning Hippo Oct 30 '13 at 20:19
  • Ok, the code I provided [does work](http://codepad.viper-7.com/ZsOuws) so the problem isn't there. This means it lies elsewhere and probably should be a new question if you can't figure it out. – John Conde Oct 30 '13 at 20:27
  • 1
    @RocketHazmat & @JohnConde: `$diff->days` and `$diff->d` are not the same things. `->days` returns the TOTAL number of days between datetimes, where `->d` only returns number of days with carry over points, so `->d` cannot be larger than 31... – Glavić Oct 30 '13 at 21:15