简体   繁体   中英

Laravel Carbon subtract days from current date

I am trying to extract objects from Model "Users" whose created_at date has been more than 30 days from today .

Carbon::now() ==> I want as ==> Carbon::now() - 30days

$users = Users::where('status_id', 'active')
               ->where( 'created_at', '<', Carbon::now())
               ->get();

How can this be achieved?

Use subDays() method:

$users = Users::where('status_id', 'active')
           ->where( 'created_at', '>', Carbon::now()->subDays(30))
           ->get();

You can always use strtotime to minus the number of days from the current date:

$users = Users::where('status_id', 'active')
           ->where( 'created_at', '>', date('Y-m-d', strtotime("-30 days"))
           ->get();

From Laravel 5.6 you can use whereDate :

$users = Users::where('status_id', 'active')
       ->whereDate( 'created_at', '>', now()->subDays(30))
       ->get();

You also have whereMonth / whereDay / whereYear / whereTime

As with strtotime or DateTime, any (relative) date expressions can also be used with carbon::parse .

$users = Users::where('status_id', 'active')
           ->where( 'created_at', '>', Carbon::parse('Now -30 days'))
           ->get();

Alternatively for 'Now -30 Days', expressions '-30days' or '-720 hours' are also possible.

'Now -30 Days' takes into account the current time. If you need a time 00:00, use 'Today -30 Days'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM