Tolure
Tolure

Reputation: 879

php date next month gives wrong day

Why does

echo date("j/m/Y", strtotime("2015/01/31 00:00 next month"));

gives 3/03/2015 and not 28/02/2015

All I'm looking for is a todays date next month and if todays date is not valid then it'll give me the last day of next month.

Upvotes: 0

Views: 469

Answers (2)

Mark Baker
Mark Baker

Reputation: 212442

$thisMonth = "2015-01-31 00:00";
$thisMonthDate = strtotime($thisMonth);
$nextMonthDate = strtotime($thisMonth . ' next month');
if (date('j', $thisMonthDate) !== date('j', $nextMonthDate)) {
    $nextMonthDate = strtotime(date('Y-m-d H:i:s', $nextMonthDate) . ' last day of previous month');
}
echo date('Y-m-d H:i:s', $nextMonthDate), PHP_EOL;

Upvotes: 3

marcosh
marcosh

Reputation: 9008

What PHP is doing here is the following:

first it adds a month to your date, arriving to "2015/02/31"

then it realizes that this date does not exist, and that it is 3 days after "2015/02/28", which, translated in human terms, is "2015/03/03"

Look here for a solution to your problem, as @kingkero suggested

Upvotes: 2

Related Questions