首页 > 解决方案 > Laravel Carbon 加或分钟一分钟用于比较时间

问题描述

我正在处理通知,然后每分钟检查一次预定通知。它从不调用它,因为我的 now 变量采用分钟格式(2021-01-28 10:27),其中存储了数据库 send_date(2021-01-28 10:15:11)

    $now = date("Y-m-d H:i", strtotime(Carbon::now()));
    
   
    $notifications = Notification::get();
    if($notifications !== null)
    {
        Log::info('Notifications are not null ' .$now); // shows in log (2021-01-28 10:27)
        $notifications->where('send_date',  $now)->each(function($message) {
        Log::info('looking at send_date'); // never shows in log
        }
     }

还是有另一种我没有看到的方法?

标签: phplaravelphp-carbon

解决方案


然后你可以使用以下方式

    $notifications->whereBetween('send_date', [Carbon::now()->startOfMinute(), Carbon::now()->endOfMinute()])->each(function($message) {

如果您需要自己格式化时间,那么:

    $notifications->whereBetween('send_date', [Carbon::now()->startOfMinute()->format('Y-m-d H:I:s'), Carbon::now()->endOfMinute('Y-m-d H:I:s')])->each(function($message) {

推荐阅读