PHP Converting DateInterval to int

user6247538 picture user6247538 · Jun 25, 2016 · Viewed 7.4k times · Source

I'm using this code:

$due_date = new DateTime($_POST['due_date']);

$today = new DateTime();
$months = $due_date->diff($today);

$months->format("%m");

$fine = 0.02 * $price * $months; // i got error in this line

$bill = $price + $fine;

I want to calculate, if someone is late to pay then they will be fined per month. And the error message is:

Object of class DateInterval could not be converted to int

Answer

user2560539 picture user2560539 · Jun 25, 2016

The error message appears because $months is not an int, but a Datetime object like this one:

DateInterval Object
(
    [y] => 0
    [m] => 4
    [d] => 12
    [h] => 6
    [i] => 56
    [s] => 9
    [weekday] => 0
    [weekday_behavior] => 0
    [first_last_day_of] => 0
    [invert] => 0
    [days] => 133
    [special_type] => 0
    [special_amount] => 0
    [have_weekday_relative] => 0
    [have_special_relative] => 0
)

You can get the integer value of months like this

$due_date = new DateTime('13-02-2016');

$today = new DateTime();
$months = $due_date->diff($today);

echo $months->m;

Check the above result in PHP Sandbox

So basically your code will look like

$due_date = new DateTime($_POST['due_date']);

$today = new DateTime();
$months = $due_date->diff($today);

$fine = 0.02 * $price * $months->m; // i got no error in this line

$bill = $price + $fine;