Conversion of Dateinterval to int in PHP

Asked

Viewed 98 times

2

I get the error

Notice: Object of class Dateinterval could not be converted to int

on line 78, where the second if. The excerpt from the code is part of a while, in that Timeframe is calculated how long since the last posting of a user on a social network. How can I fix this mistake?

//Timeframe
        $date_time_row = date("Y-m-d H:i:s");
        $start_date = new DateTime($date_time); //Time of post
        $end_date = new DateTime($date_time_row); //Current time
        $interval = $start_date->diff($end_date); //Difference between dates
        if($interval->y >= 1) {
            if($interval == 1)
                $time_message = $interval->y . " year ago"; //1 year ago
            else 
                $time_message = $interval->y . " years ago"; //1+ year ago

        }

When you post something, it is reset when I refresh the page, showing an error for each user post. Posts are shown correctly at the bottom of the page, but the error remains.

2 answers

2


Simple mistake:

The variable $interval is an object and not an entire. You are comparing two different things, php tries to convert the object into an integer to make the comparison with number 1 but cannot.

Following your logic, I believe what you want is:

if($interval->y == 1) // pegar a diferença de anos "y" e ver se é igual a 1

If the $interval were a numeric string or a true Boolean:

$interval = true;
if($interval == 1)

He would pass by if no problem at all.

  • I used $interval = true;
if($interval == 1)and I get the error: Trying to get Property 'y' of non-object, same for months, days and hours.

  • @Andrécavalcante yes... But it’s not for you to do this. This was just to show that php, does this conversion naturally. Use the first example of if I showed you.

1

I believe this doubt can be easily resolved.
In this code snippet you are using the object interval to compare with an interim.

if($interval->y >= 1) {
    if($interval == 1)
        $time_message = $interval->y . " year ago"; //1 year ago
    else 
        $time_message = $interval->y . " years ago"; //1+ year 
}

To solve you must compare the attribute y of interval with 1 as follows:

if($interval->y >= 1) {
    if($interval->y == 1)
        $time_message = $interval->y . " year ago"; //1 year ago
    else 
        $time_message = $interval->y . " years ago"; //1+ year 
}

But you can still simplify the operation using a ternary operator:

if($interval->y >= 1) {
    $time_message = ($interval->y == 1) ? $interval->y." year ago" :$interval->y . " years ago";
}

I hope I’ve helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.