Calculate difference between two dates - I can not convert the date of the database to DateTime

1

Good afternoon!

I made a function to calculate the difference of days between two dates, one of these dates is the current one (which I create using new DateTime() ) and the other one gets 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 do I create the column:

$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

    
asked by anonymous 26.03.2017 / 19:38

3 answers

3

The problem is in the variable $ DataEvent. It is 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;
}
    
26.03.2017 / 20:02
1

Assuming that $eventos is an array with Eloquent models , you can automatically convert attributes using #

<?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'
    ];
}

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

    
26.03.2017 / 20:15
1

There is 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 questions please send me:)

    
26.03.2017 / 20:50