Calculate difference between two dates - I cannot convert the database date to Datetime

Asked

Viewed 1,085 times

1

Good afternoon!

I made a function to calculate the difference of days between two dates, one of these dates is the current one (I create using the new DateTime()) and the other picks up in the database and is saved as datetime

foreach ($eventos as $e) {
    $qtdDias = $this->calculaDiferenca($e->dataEv);
    if ($qtdDias > 0 && $qtdDias <= 7) {
       array_push($evs,$e->id);
    }
}
function calculaDiferenca($DataEvento){
    $hoje = new DateTime();
    $diferenca = $hoje->diff($DataEvento);
    return $diferenca->d;
}

How I create the spine:

$table->datetime('dataEv')->nullable();

When I run the error on the line where I calculate the difference:

Datetime::diff() expects Parameter 1 to be Datetimeinterface, string Given

  • The return of dd($e->dataEv) have what as a result? See the error message, is returning a string, not a DateTime

  • I know, that’s the problem. I need to convert this string into a Datetime

  • What is the format/content of this returned string ?

3 answers

3


The problem is in the $Dataevent variable. It is of the string type and not Datetime. You need to transform it to the Datetime object

function calculaDiferenca($DataEvento){
    $hoje = new DateTime();
    $diferenca = $hoje->diff(new DateTime($DataEvento));
    return $diferenca->d;
}
  • Wow, I believe that was it! Thank you!

1

Assuming $eventos is a array with models of Eloquent, you can automatically convert attributes using a Date Mutator

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Eventos extends Model
{
    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = [
        'created_at',  // Mantenha esses dois caso sua tabela tenha timestamps
        'updated_at',
        'dataEv'
    ];
}

Thereby $e->dataEv return an instance of Carbon, which is a subtype of DateTime and already works with your code.

1

There’s an easier way...

$data_inicial = '2013-08-01';
$data_final = '2013-08-16';

$diferenca = strtotime($data_final) - strtotime($data_inicial);
//Calcula a diferença em dias
$dias = floor($diferenca / (60 * 60 * 24));

echo "A diferença é de $dias entre as datas";

Any doubt rules you :)

Browser other questions tagged

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