When I try to get the last day of next month by PHP or Laravel carbon, everything is ok, but when I try to get the last day of next month from a specific date, 2023-01-31, by
date('Y-m-01', strtotime('next month', strtotime('2023-01-31')));
OR
Carbon::createFromFormat('Y-m-d H:m:00:000', '2023-01-31')->addMonth()->format('Y-m-t H:m:00:000');
That time output results are given on 2023-03-31, but the last day of next month is 2023-02-28. So how can I solve it? It’s not working correctly.
$instituter = Institute::where('code', $instInfo->institute_code)->first();
// $institute = Carbon::createFromFormat('Y-m-d H:m:00:000', $institute->institute_expire)->addMonth()->format('Y-m-d H:m:00:000');
// $expire = $instituter->institute_expire;
// $inst = Carbon::createFromFormat('Y-m-d H:i:00.000', $instituter->institute_expire)->addMonths(6)->startOfMonth()->format('Y-m-d');
$inst = date('Y-m-01', strtotime('next month', strtotime($instituter->institute_expire)));
// $inst = Carbon::createFromFormat('Y-m-d H:i:00.000', $instituter->institute_expire)->addMonths(6)->startOfMonth();
// $institute = Carbon::createFromFormat('m/d/Y', $instituter->institute_expire)->addMonth();
4
Answers
t => number of days in the month
strtotime will do this …
e.g.
echo date('c', strtotime('last day of next month'));
gives e.g. 2023-02-28T19:53:34+00:00, when today is 2023/01/21.
Alternatively –
ècho (new DateTime('last day of next month'))->format('c')
will also work
A date is given as a string.
Based on this date, a date object is to be created for the last day of the following month. With DateTime this can be done in one line.
Carbon is an extension of DateTime. Therefore this also works:
If the date already exists as an object, it becomes even easier.
This works exactly the same with carbon again.
Beware of solutions with addMonth() with Carbon or just ‘next Month’ for DateTime. Older versions also return incorrect results for the date "2023-01-31" as with the question. Carbon has a special method for adding months ‘without overflow’: addMonthsNoOverflow()
From Laravel 5.5 you can use now() function to get the current date and time and you can get the last date of next month using :
if you want to format to Y-m-d
or if you want to get only date change format to $now->format(‘d’);
if you are using laravel version less than 5.5 using the above functions as