Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP get a date one month later [duplicate]

Tags:

php

<?php

echo "\n";
echo $end_date = date('Y-m-d', strtotime('+1 month'));
echo "\n";
$today = date("Y-m-d"); // 2012-01-30
echo $next_month = date("Y-m-d", strtotime("$today +1 month"));
echo "\n";
$end_date = mktime(date("H"), date("i"), date("s"), date("n") + 1, date("j"), date("Y"));
echo "\n" . date('Y-m-d',$end_date);

http://codepad.org/bHiNFIBR

How can I get the correct date +1 months I tried these options. all returned 1 May but I need April 30

like image 591
Bugaloo Avatar asked Mar 31 '14 07:03

Bugaloo


2 Answers

Try something like that..

if( date('d') == 31 || (date('m') == 1 && date('d') > 28)){
    $date = strtotime('last day of next month');
} else {
    $date = strtotime('+1 months');
}

echo date('Y-m-d', $date);

But just note that when you are 31st March as +1month its correct to target 1st of May not 30th April :)

like image 99
Svetoslav Avatar answered Sep 29 '22 12:09

Svetoslav


I'd suggest this:

$next_month = date('Y-m-d', strtotime("+1 months", strtotime("NOW"))); 

EDIT

function addMonth($date) {
    $date = new DateTime($date);
    $day = $date->format('j');

    $date->modify("+1 month");
    $next_month_day = $date->format('j');

    if ($day != $next_month_day)
        $date->modify('last day of last month');

    return $date;
}

$next_month = addMonth(time());
echo $next_month->format("Y-m-d");

hope this helps :-)

like image 42
ponciste Avatar answered Sep 29 '22 10:09

ponciste