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

时间:2015-10-31 00:03:45

标签: php datetime date-comparison

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..

2 个答案:

答案 0 :(得分:3)

我用它来处理我的数据库日期

    //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);

答案 1 :(得分:1)

如果我得到你想要的东西,你可以使用strtotime功能。它将传递给它的日期时间字符串转换为Unix时间戳,您可以将其用于比较。

如果日期来自2015-10-21,那么该函数将返回1445385600,如果今天date(Y-m-d)的日期是2015-10-31,那么该函数将返回{{1}所以你可以轻松地比较两者。

1446249600

然后可以将比较作为$var1 = strtotime('2015-10-21'); $var2 = strtotime('2015-10-31');