Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: querying for all records with a timestamp from today

I have an Orders table that has a field scan_date in unix timecode. I am trying to get all Orders with a scan_date WITHIN the current day. I was originally using whereBetween() to grab orders within the last 24 hours of whenever it's run but I realized that's not doing exactly what I need.

->whereBetween('scan_date', [Carbon::now()->addDays(-1), Carbon::now()])

If an order has a scan_date between 12:01AM and 11:59pm on the current day, I want to grab all those orders -- is this possible to query for?

like image 247
burtonLowel Avatar asked Oct 17 '25 03:10

burtonLowel


2 Answers

Similar to what you were doing, with a small modification:

$today = \Carbon\Carbon::today();
$startOfDayTimestamp = $today->copy()->startOfDay()->timestamp;
$endOfDayTimestamp = $today->copy()->endOfDay()->timestamp;

->whereBetween('scan_date', [
    $startOfDayTimestamp,
    $endOfDayTimestamp
])
like image 71
porloscerros Ψ Avatar answered Oct 18 '25 19:10

porloscerros Ψ


You can use whereDate, on Laravel < 5.7 you should format the date to Y-m-d before passing it:

->whereDate('scan_date', Carbon::now()->toDateString())

On Laravel >= 5.7 you can pass an instance of DateTimeInterface directly:

->whereDate('scan_date', Carbon::now())
like image 40
Hafez Divandari Avatar answered Oct 18 '25 18:10

Hafez Divandari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!