Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add date in php gives different results

I have to get a date which is 6 months added with specific date. I used the following code

$start_date = "2016-08-30";
$end_date= date( "Y-m-d", strtotime( "$start_date +6 months" ) );
echo $end_date;

which gave result as 2017-03-02
Then I changed the start date in code as below

$start_date = "2016-09-01";
$end_date= date( "Y-m-d", strtotime( "$start_date +6 months" ) );
echo $end_date;

which is giving result as 2017-03-01
Why is this happening at first place? Is there anything wrong with my code?
Using Mysql query

SELECT DATE_ADD('2016-08-30', INTERVAL 6 MONTH)

gives result 2017-02-28
Which is the right solution to get the correct date?

like image 895
Thejas Avatar asked Sep 01 '16 06:09

Thejas


1 Answers

This happens due to PHP's behavior. In this case 6 months are added which gives february(it has 28 days) so it adds three more days , but in MySQL it adds only months.

To solve this use last day of 6 month or last day of sixth month instead of +6 months

Code

$date = new DateTime( '2016-08-30' );
echo $date->format( 'Y-m-d' ), "\n";
$date->modify( 'last day of sixth month' );
echo $date->format( 'Y-m-d' ), "\n";

Code Demo

Output

2016-08-30
2017-02-28

Another Solution

$date = new DateTime( '2016-08-25' );
echo $date->format('Y-m-d'),"\n";
$day = $date->format('j');
$date->modify('first day of sixth month');
$date->modify('+' . (min($day, $date->format('t')) - 1) . ' days');
echo $date->format('Y-m-d');

Code Demo

Output

2016-08-25
2017-02-25

Also refer Relative Formats

like image 119
zakhefron Avatar answered Sep 18 '22 16:09

zakhefron