I'm currently receiving Carbon dates like: 2021-03-17 17:14:42.01811, and I would like to not consider hours, minutes and seconds, converting it to the start of the day.
This value is not meant to be formatted to a string because in the code it is used for comparison against other dates.
I managed to make a solution, but it doesn't seem to be the most valid one, I'm using now()
function as an example.
\Carbon\Carbon::parse(\Carbon\Carbon::now()->format('Y-m-d'));
Is there a more correct way to do this operation?
You can use the hour
, minute
and second
setters of Carbon.
$dt = Carbon::now();
$dt->hour = 0;
$dt->minute = 0;
$dt->second = 0;
Or the fluent setters:
$dt = Carbon::now()
->hour(0)
->minute(0)
->second(0);
Or use fluent setter setTime($hour, $minute, $second = 0, $microseconds = 0)
which also sets the microsecond to zero:
$dt = Carbon::now()->setTime(0, 0)