3

I'm using code that works fine on all dates, except 2015-05-31. The code brings me the first day of next month. it works on every date, even if day of month is 31.

$time = strtotime('2015-07-31');
$final = date("Y-m-1", strtotime("+1 month", $time));
echo $final;

output will be --> 2015-08-1.

For some reason on the date 2015-05-31 it returns 2015-07-1 instead of 2015-06-01

$time = strtotime('2015-05-31');
$final = date("Y-m-1", strtotime("+1 month", $time));
echo $final;

Its probably because 6-2014 has 30 days, and 8-2014 has 31 days, so +1 month adds 30 days and not a "month".

How could i get correctly the first day of next month on every date?

Thank you.

BenB
  • 2,747
  • 3
  • 29
  • 54

2 Answers2

5

I think this should work -

$time = strtotime("2015-05-31");
echo $final = date("Y-m-d", strtotime("first day of next month", $time));
TBI
  • 2,789
  • 1
  • 17
  • 21
  • It does not understand to string, the return is "1969-12-31". May be depends on php version. Yes, >=5.3 – Cheery Sep 30 '14 at 06:09
-1

You can try like this:

<?php
$date = new DateTime('2000-12-31');
$interval = new DateInterval('P1M');

$date->add($interval);
echo $date->format('Y-m-d') . "\n";

$date->add($interval);
echo $date->format('Y-m-d') . "\n";
?>

Output:

2001-01-31
2001-03-03

For more information :http://in3.php.net/manual/en/datetime.add.php

Suresh Kamrushi
  • 15,627
  • 13
  • 75
  • 90
  • If you run your code on 2015-05-31 the output will be "2015-07-01 2015-08-01". same problem. – BenB Sep 30 '14 at 05:44