Rex Rex
Rex Rex

Reputation: 1030

Given date + 2 months working wrong for december 30,31

I want to get first date of +2 months of given date,Iam using below function to get this .

$date = '2015-12-31';
echo $date = date('1-m-Y', strtotime('+2 month', strtotime($date)));

This was working fine.But for december 30,31 this is not giving result as expected.for date 2015-12-30 it gives result '1-03-2016'.I know because of february having 29 days this gives this result.But expected result is '01-02-2016'. This can be solved by writing new function.But i want to go with built in functions.Please Help.

Upvotes: 0

Views: 93

Answers (2)

Thamilhan
Thamilhan

Reputation: 13303

Coming to your way, convert your date to 1st of your desired month and then calculate. Like this:

<?php
$date = '2015-12-31';
$date = date('1-m-Y', strtotime($date));
echo $date = date('1-m-Y', strtotime('+2 months',strtotime($date)));

You get:

1-02-2016


Instead, you can use first day of +2 months:

echo $date = date('d-m-Y', strtotime('first day of +2 months',strtotime($date)));

Will output (as you desire):

01-02-2016

Upvotes: 1

CodeBoy
CodeBoy

Reputation: 3300

date('Y-m-d', strtotime('first day of +2 month', strtotime($date)));

first day of maps 2015-12-30 to 2015-12-01 then +2 month maps it to 2016-02-01. By mapping to the 1st day of month of your starting date BEFORE adding +2 months, you don't have to to worry about short months.

Upvotes: 1

Related Questions