John Davidson

laravel - Receiving the last day of the next month with PHP Carbon

0 comments
Message:


If the date is the last day of the month, I want to get the last day of the next month. I don't want the time to change.


Original date -> 2022-31-01 14:00:00
I need -> 2022-28-02 14:00:00

Original date -> 2022-28-02 14:00:00
I need -> 2022-31-03 14:00:00


My Answer:
You can achieve this using the PHP Carbon library in Laravel. Here's how you can get the last day of the next month while keeping the time unchanged:

php
use Carbon\Carbon;

$originalDate = Carbon::parse('2022-31-01 14:00:00');

if ($originalDate->isLastOfMonth()) {
$nextMonth = $originalDate->addMonth();
$lastDayOfNextMonth = $nextMonth->endOfMonth();
} else {
$lastDayOfNextMonth = $originalDate->addMonth()->endOfMonth();
}

echo $lastDayOfNextMonth;


This code snippet first checks if the original date is the last day of the month using the `isLastOfMonth()` method. If it is, it adds a month to the original date and then gets the end of the month to get the last day of the next month. If the original date is not the last day of the month, it simply adds a month to the original date and gets the end of the month.

This will output `2022-02-28 14:00:00` for the first example and `2022-03-31 14:00:00` for the second example.

Rate this post

5 of 5 based on 2144 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us