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();
CodePudding user response:
You can use the endOfMonth()
method in Carbon to get the last day of the next month, like the following.
$date = Carbon::createFromFormat('Y-m-d', '2023-01-31');
$nextMonth = $date->addMonth()->endOfMonth();
echo $nextMonth->format('Y-m-d');
This will output 2023-02-28
.
CodePudding user response:
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
CodePudding user response:
$next_month_last_date = date("Y-m-t", strtotime(" 1 month"));
t => number of days in the month