Home > Software engineering >  how to compare today to another date with where
how to compare today to another date with where

Time:01-03

I need to compare today to the date twenty business days after from created_at. I have afterTwentyBusinessDays function. Is it possiple to use it with where in laravel?

->where(afterTwentyBusinessDays($created_at), today())

CodePudding user response:

You have to get a date that was twenty days ago and then set in where condition

->whereDate('created_at', date('Y-m-d', strtotime('-20 days')));

CodePudding user response:

I presume afterTwentyBusinessDays($created_at) return carbon date time object.

Try $query->whereDate('created_at', '>', afterTwentyBusinessDays($created_at))

CodePudding user response:

The most efficient way is to use carbon

now()->diffInDays('2023-1-23 07:06:31')     // 19

now() will give you carbon instance alongwith UTC date and time. You can compare any dates, years, months, months, weeks even seconds.

Explore Carbon docs or visit detailed Carbon methods and their uses

https://www.digitalocean.com/community/tutorials/easier-datetime-in-laravel-and-php-with-carbon

Why you are not using Eloquent Model's own predefined methods to compare date and times like whereDate(), whereDay(), whereMonth() or wheryear() there are many.

Also you can play with these days, remember to parse in your timezone and format

User::whereDay('created_at', '>', '2023-1-23 07:06:31')->get();
  • Related