user7078503
user7078503

Reputation:

Get all results from within the hour

I'm trying to get all results within the hour. NOT THE PAST HOUR, but WITHIN THE HOUR.

For example, if it's currently 12:30, I want to get all results since 12:00, not 11:30. Or if it's 6:45, I want to get all results since 6:00, not 5:45.

How can I do this using Carbon and Laravel?

Here's what I've got so far:

$user = User::where('created_at', WHAT DO I PUT HERE)
    ->get();

Upvotes: 3

Views: 2243

Answers (5)

Saumya Rastogi
Saumya Rastogi

Reputation: 13693

You can use whereBetween method for this.

User::whereBetween('created_at', [date('Y-m-d H:00:00'), date(Y-m-d H:i:s)])->get();

Upvotes: 0

smartrahat
smartrahat

Reputation: 5609

To do this you have to get current hour with no minute and second. Then run a query to return result after that time.

$currentHourInt = Carbon::now('Asia/Dhaka')->hour; 
$currentHour = Carbon::createFromTime($currentHourInt,0,0);

$user = User::where('created_at','>',$currentTime)
            ->get();

In the above example $currentHourInt will return the integer value of current time. Example, if it is 13:54:12 it will return 13. I used Aisa/Dhaka as my timezone you can use yours or leave it blank if your data saved in UTC time. The $currentHour creates current time with current hour, 0 min and 0 sec. Example, if it is 13:54:12 it will return 13:00:00.

For more information about Carbon: http://carbon.nesbot.com/docs/

Hope it will help

Upvotes: 0

schellingerht
schellingerht

Reputation: 5796

I know, you're looking for a Carbon solution. For readability and portability reasons below a native OOP PHP DateTime solution.

$user = User::where('created_at', '>=', (new DateTime)->format('Y-m-d H:00:00'))
->get();

Notice the >= operator!

Upvotes: 1

Amit Gupta
Amit Gupta

Reputation: 17658

You can do this with simple PHP date() function as

$user = User::where('created_at', '>', date('Y-m-d H:00:00'))->get();

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163758

You can use Carbon's now() and subHour() methods:

$user = User::where('created_at', '>', Carbon::now()->subHour())->get();

Upvotes: 0

Related Questions