user6247538
user6247538

Reputation:

PHP Converting DateInterval to int

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

Upvotes: 9

Views: 12377

Answers (3)

iblanco
iblanco

Reputation: 61

Peter Darmis's answer is wrong. I can't downvote nor comment it so I will add this new answer.

DateInterval represents a period of time by deconstructing the interval in different parts, years, months, days etc... So "m" in the proposed solution will never be bigger than 12.

So you should probably do something like this:

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

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

$months = ($diff->y * 12) + $diff->m;

echo $months;

Check it in the sandbox: http://sandbox.onlinephpfunctions.com/code/907b39ffee4586c4c9481ff3e0ea1aeb2d27c7b8

Upvotes: 2

user2560539
user2560539

Reputation:

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;

Upvotes: 7

Pevara
Pevara

Reputation: 14310

You calculate the difference in months, but you never actually use that value. The format method outputs something, but doesn't change the actual DateInterval.

Try it like this:

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

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

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

$fine = 0.02 * $price * $months;

$bill = $price + $fine;

Upvotes: 2

Related Questions