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

squibby's avatar

How to force carbon time to 00:00

When using Carbon to create dates like this:

$start = new Carbon('first day of last month'); $end = new Carbon('last day of last month');

I am able to get the dates I require but the time is always set to the current time. How can I force the time to be 00:00:00

So instead of 2016-06-01 05:18:21 I want to get 2016-06-30 00:00:00

Thanks for looking.

0 likes
4 replies
martinbean's avatar
Level 80

@squibby You can use the startOfDay() method:

Carbon::parse('some string')->startOfDay()

On a side note, there’s also endOfDay() for the reverse (i.e. to set the time 23:59:59).

Alternative, in your scenario, you could do:

$firstDayOfLastMonth = Carbon::today()->subMonth()->startOfMonth();
$lastDayOfLastMonth = Carbon::today()->subMonth()->endOfMonth();

Ran today (26 July) that would yield 2016-06-01 00:00:00 and 2016-06-30 23:59:59 respectively, which is handy for things like reporting periods.

12 likes
Prullenbak's avatar
$start = new Carbon('first day of last month')->startOfDay(); 
$end = new Carbon('last day of last month')->endOfDay();
4 likes
Prullenbak's avatar

Be careful though. If I remember correctly, subMonth() doesn't work as you'd expect if the day doesn't exist in the previous month (for example on march 30th).

So better would be:

Carbon::today()->startOfMonth()->subMonth();
Carbon::tody()->startOfMonth()->subMonth()->endOfMonth();

because the first second of a month always exists ;)

2 likes

Please or to participate in this conversation.