0

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.

Rex Rex
  • 1,030
  • 1
  • 8
  • 29

2 Answers2

1

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

Thamilhan
  • 13,040
  • 5
  • 37
  • 59
1
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.

BareNakedCoder
  • 3,257
  • 2
  • 13
  • 16