Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

abhishek009's avatar

Carbon match by Date, Month and Year

Hi,

I'm using Carbon in Laravel 5.5. I have stored record as timestamp which has 2017-10-17 19:59:49 , 2017-10-17 19:59:50 , 2017-10-17 20:00:01 values.

I'm using date and time picker to pick date , month and year. This is my query of to match by date, month and year but it is not working.

Where selected date comes from the date and time picker. The result of Carbon::parse($selected_date); is this: 2017-10-17 00:00:00

$Get = GetRecords::where("student_id",$id)->where("record","=",Carbon::parse($selected_date))->first();

The following query is not working. Any guesses ?

0 likes
8 replies
ftrillo's avatar

Try calling toDateString() on the Carbon object. You also don't need the '=' argument, that's the default.

GetRecords::where("student_id",$id)->where("record", Carbon::parse($selected_date)->toDateString())->first();

If that doesn't work try calling whereDate, instead of where. Although that shouldn't be necessary.

1 like
abhishek009's avatar

Ok. I have done debugging. It is able to match 2017-10-17 00:00:00 this date but the query doesn't match when it has time in it like 2017-10-17 19:59:49

Cronix's avatar

is your $selected_date set to the same timezone as your database is set to? By default the database is in UTC. You may need to Carbon::parse($selected_date, 'UTC')->toDateTimeString(); or whatever timezone the user submitting the date is in.

abhishek009's avatar

I have web hosting from the India and also I have set the timezone to "Asia/Kolkata". But still.

ftrillo's avatar
ftrillo
Best Answer
Level 4

If you want to match only year, month and day, ignoring time, you have to use whereDate to compare with a date string. Like so:

$query->whereDate('record', '=', $carbonObject->toDateString());
1 like
Cronix's avatar

Strange. I tried it on my user table using the created_at field and it works fine.

$user = App\User::where('id', 1)->where('created_at', '2017-04-26 17:33:21')->first();

If I change it to 1 second later, it doesn't get the result. Are you sure there is a student with that ID AND they have that datetime in the db? Try a raw query in tinker or something and remove the datetimepicker and eloquent from the equation.

Please or to participate in this conversation.