Jeremiah S.
Jeremiah S.

Reputation: 421

Laravel Carbon plus or minute one minute for comparing time

I am working on a notification then checks every minute for a scheduled notification. It never calls it because my now variable is in a minute format (2021-01-28 10:27) where as the database send_date is stored (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
        }
     }

Or is there another way of doing this, that I am not seeing?

Upvotes: 1

Views: 2054

Answers (2)

bhucho
bhucho

Reputation: 3420

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

Reference :
whereBetween, Carbon

Upvotes: 2

diego182
diego182

Reputation: 126

Then you could use the following way

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

If you need to format the time yourself then:

    $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) {

Upvotes: 2

Related Questions