carbon compare date check if date day is equal to current day
Asked Answered
S

3

9

I want to compare if the post date day is equal to the current day. But below example is not working. Do you know why? The date column is of "datetime" type.

$post= Post::Query();
…
elseif($range == "week") {
    $post= $post->where('date', <', Carbon::now()->addDays(7));
}
elseif($range == "day") {
    $post= $post->where('date', '=', Carbon::today());
}
....

When the user selects the current day in the select menu, no results appear, but select week works.

Scales answered 13/7, 2018 at 13:9 Comment(1)
Carbon::today() includes the time at 00:00:00Withdraw
M
25

Look for method isSameDay() on carbon docs:

$dt->isSameDay($dt2);

Remeber to parse the date, you must use two Carbon objects...

Medrek answered 28/3, 2019 at 19:58 Comment(1)
Unfornately this doesnt work. I parse 2 dates, I print the dates and I see this: 2023-06-27 08:00:00 and 2023-06-29 08:00:00 and yet Carbon thinks its the same dayIal
L
1

Try this one, I am assuming that your only comparing to a date.

…
elseif($range == "week") {
    $post= $post->whereDate('date', <', Carbon::now()->addDays(7)->format('Y-m-d'));
}
elseif($range == "day") {
    $post= $post->whereDate('date', '=', Carbon::today()->format('Y-m-d'));
}
Ludie answered 13/7, 2018 at 13:17 Comment(0)
W
0

Laravel has build in Query Builder functions to work with dates, such as whereDate. So you can do:

$post = $post->whereDate('date', '=', Carbon::today());

This will make sure the time part of the Carbon date is not included.

Withdraw answered 13/7, 2018 at 13:19 Comment(1)
Thanks, but also dont works. With week works with where instead of whereDate.Scales

© 2022 - 2024 — McMap. All rights reserved.