What's the right way to compare two dates in php?

Zakaria picture Zakaria · Oct 31, 2015 · Viewed 7.6k times · Source

I need to compare the dates from my database with the current day. This id my code, in eloquent:

$posts = Post::where('date', '=', date('Y-m-d'))->get();

I want to retrieve today's posts only. Knowing that the 'date' field is of type Date, How do I make this work? I tried to convert date('Y-m-d') to string with the 'format' method, but it seems that date('Y-m-d') is somehow returning a Boolean, and thus, the method 'format' can't be applied to it..

Answer

konnection picture konnection · Oct 31, 2015

I use this to handle my database dates

    //Get the database date, and format it

$database_date = date_format($database_date, 'Y-m-d');

//Get today date or another date of you choice
$today_date = new DateTime();

//Format it
$today_date = date_format($today_date, 'Y-m-d');

// Use strtotime() to compare the dates or DateTime::diff for more cleaner IMO
$difference = strtotime($today_date) - strtotime($database_date);