Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the date for 29th last month, two months ago, etc

Tags:

date

php

I'm looking to find the date of the 29th of this month, the 29th of next month, the 29th of last month and so on...

I know you can use this kind of code to find days of the week:

$friday_last = date("d/m/Y", strtotime("last Friday"));
$friday_due = date("d/m/Y", strtotime("this Friday"));

Is there a similar way to find a certain day (29th) of each month or would I have to use a different code?

like image 409
Snappysites Avatar asked Dec 06 '25 07:12

Snappysites


1 Answers

You need to use DateTime() as it makes working with dates much easier. You'll notice I start by going to the first day of each month. That's so this doesn't break when you get to the 29th-30th of each month as weird date things start to happen.

echo (new DateTime())->modify('first day of this month')->format("29/m/Y");
echo (new DateTime())->modify('first day of previous month')->format("29/m/Y");
echo (new DateTime())->modify('first day of next month')->format("29/m/Y");

Demo

echo (new DateTime())->modify('first day of this month')->modify('-2 months')->format("29/m/Y");

Demo

like image 159
John Conde Avatar answered Dec 08 '25 20:12

John Conde