问题
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..
回答1:
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);
回答2:
If i am getting what you want, you can make use of strtotime function. It converts datetime string passed to it to Unix timestamp which you can use for comparison.
If date from 2015-10-21
then the function will return 1445385600
and if today's date from date(Y-m-d)
is 2015-10-31 then the function will return 1446249600
so you can compare the two easily.
$var1 = strtotime('2015-10-21');
$var2 = strtotime('2015-10-31');
Then comparison can be made as if($var1 == $var2)
来源:https://stackoverflow.com/questions/33446581/whats-the-right-way-to-compare-two-dates-in-php