【问题标题】:What's the right way to compare two dates in php? [duplicate]在php中比较两个日期的正确方法是什么? [复制]
【发布时间】:2015-10-31 00:03:45
【问题描述】:

我需要将数据库中的日期与当天进行比较。这是我的代码,雄辩:

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

我只想检索今天的帖子。 知道“日期”字段的类型为日期,我该如何进行这项工作? 我尝试使用“格式”方法将date('Y-m-d') 转换为字符串,但似乎date('Y-m-d') 以某种方式返回布尔值,因此无法将“格式”方法应用于它..

【问题讨论】:

标签: php datetime date-comparison


【解决方案1】:

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

如果日期来自 2015-10-21,则函数将返回 1445385600,如果今天来自 date(Y-m-d) 的日期是 2015-10-31,则函数将返回 1446249600,以便您轻松比较两者。

$var1 = strtotime('2015-10-21');

$var2 = strtotime('2015-10-31');

那么可以比较为if($var1 == $var2)

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多