-1

Given a string like 2016-05-25 I want to get the first day of the previous month (e.x 2016-04-01).

I have tried this

$month_ini = new DateTime("first day of last month"); 
$month_end = new DateTime("last day of last month");

but I get the first day of the previous month relative with the current month, which is not what I want.

Specifically I will get random dates from clients (with format 'Y-m-d') and I have to display the first day of the previous months relative with the client's requested month.

dios231
  • 714
  • 1
  • 9
  • 21
  • 1
    soooo.. WHAT exactly have you tried so far to achieve this? – Franz Gleichmann Sep 29 '16 at 15:14
  • "I want to get the first day of the previous month" - that's nice, so why don't you, then? – neminem Sep 29 '16 at 15:14
  • I dont want to get the first day of the previous month....I want given a random date string like the one I have at my question retrieve the last day of the previous month – dios231 Sep 29 '16 at 15:16
  • the answered that marked as duplicate did not help me – dios231 Sep 29 '16 at 15:17
  • what you want to do with day AND month, the linked answer does with just the day. it shouldn't be too hard to apply the same method to the month. – Franz Gleichmann Sep 29 '16 at 15:18
  • The linked answer display what I want compared with the current month. I want to retrieve the first day of the last month compared a random date string...it not the same – dios231 Sep 29 '16 at 15:19

4 Answers4

1

Here's how to do this for any month, instead of the current month

$date = new DateTime('2016-05-25');
$date->modify('-1 month');
echo $date->format('Y-m-t'); // 2016-04-30
echo $date->format('Y-m-01'); // 2016-04-01
Machavity
  • 30,841
  • 27
  • 92
  • 100
  • This solution is wrong in some case. you would try if the ```$date``` is 2016/12/31 – Kenneth Chan Dec 31 '16 at 05:44
  • @KennethChan Yeah. `modify` is screwy on months. Which is why [the manual says](http://php.net/manual/en/datetime.modify.php) `Beware when adding or subtracting months` – Machavity Dec 31 '16 at 15:46
1

Pre-Request: System should be in UTC

$firstDayLastMonth = date('Y-m-d', strtotime('first day of last month'));
$lastDayLastMonth = date('Y-m-d', strtotime('last day of last month'));
echo $firstDayLastMonth .'<br>'. $lastDayLastMonth ;
0

This works for any month:

$datestart = date('Y-m-01',mktime(0, 0, 0, date("m")-1, 1, date("Y")));
$dateend   = date('Y-m-t' ,mktime(0, 0, 0, date("m")-1, 1, date("Y")));
-1

The solution I used is like that:

$date = new DateTime('2016-12-31');
$date->modify('FIRST DAY OF -1 MONTH');
echo $date->format('Y-m-d'); //2016-11-01
Kenneth Chan
  • 532
  • 4
  • 20