在php中比较两个日期的正确方法是什么? [英] What's the right way to compare two dates in php?
本文介绍了在php中比较两个日期的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将数据库中的日期与当天进行比较。这是我的代码,雄辩:
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();
我只想检索今天的帖子。
知道日期字段的类型为日期,我该如何进行这项工作?
我尝试使用'format'方法将 date('Ym-d')
转换为字符串,但似乎 date( 'Ym-d')
某种程度上返回了布尔值,因此无法将'format'方法应用于它。.
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..
推荐答案
我用它来处理我的数据库日期
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);
这篇关于在php中比较两个日期的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文