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.
@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.
$start = new Carbon('first day of last month')->startOfDay();
$end = new Carbon('last day of last month')->endOfDay();
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 ;)
Please sign in or create an account to participate in this conversation.