Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding 2 months in PHP

Tags:

date

php

I've seen previous problems about adding two months to an existing date, however the existing answers do not help me much as I am getting different results than what I want. I have set up a date as follows:

$date = "2014-12-31";
$date = date('Y-m-d', strtotime("$date +2 month"));

After I've added 2 months, I print it:

echo $date;

My result:

2015-03-03

but this is not right to me because this is a full month beyond what I actually want:

2015-02-28

How can I do this?

like image 381
taebu Avatar asked Oct 21 '25 03:10

taebu


2 Answers

I would use PHP's DateTime class.

$date = new DateTime('2014-12-31');
$date->modify('+2 month');
$date->format('Y-m-d');
echo $date;

It also depends on what you are expecting by 2 months, this can vary based on how many days in the month there are. Are you going by 30 days, 31 days, last day of month, first day of month?...etc.

Maybe you are looking for this,

$date = new DateTime('2014-12-31');
$date->modify('last day of +2 month');
$date->format('Y-m-d');
echo $date;

This may also help you. Relative Formats

like image 178
EternalHour Avatar answered Oct 23 '25 17:10

EternalHour


You can use DateTime class and modify method argument like last day of second month

$date = new DateTime('2014-12-31');
$date->modify('last day of second month');
echo $date->format('Y-m-d');

Edit::

modify can have multiple possible arguments

last day of 2 month

last day of +2 month

like image 39
fortune Avatar answered Oct 23 '25 16:10

fortune



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!