User_FTW
User_FTW

Reputation: 524

'Round' up a date to the beginning of the next month

I need to take an existing date from a variable and display a date that is always the 1st day (01) of whatever the next month is (and accounting for the year as well).

So if I have this:

$date = '2017-03-17'; // YYYY-MM-DD

I need to take that date and make it output this:

2017-04-01 // The first day of the next month

Just another example...

$date = '2017-12-23'; // YYYY-MM-DD

...should be converted to...

2018-01-01 // The first day of the next month

Upvotes: 1

Views: 1342

Answers (3)

Nishant Nair
Nishant Nair

Reputation: 1997

you can get it using

$date = '2017-03-17';
echo date('Y-m-01', strtotime('+1 month',strtotime($date)));

https://eval.in/790237

Upvotes: 0

Mihai Matei
Mihai Matei

Reputation: 24276

You can use DateTime like:

$dateTime = new DateTime('2017-03-17');
$dateTime->modify('first day of next month');

echo $dateTime->format('Y-m-d');

Upvotes: 6

Sougata Bose
Sougata Bose

Reputation: 31749

Simply increment the date by 1 month and set the date to 1st of the month. Do -

date('Y-m-01', strtotime('+1 MONTH', strtotime($date)));

Working code

Upvotes: 0

Related Questions