How to find the first day of current month in php

Ask a question
0

I need to aggregate all data in MySQL table which is older than the current month. Expect the current month. So now I should find all records that are older than the first day of the current month. I use php $now = new \DateTime() which returns . the current date and now I need to replace the day with 1 or 01. So what is the best way to do it?

Coin iconoffer bounty
add comment

1 Answer

0

I have found a very nice way to do it. It works with PHP 7.1 I guess with other versions as well

$startOfCurrentMonth =  new \DateTime('first day of this month');

BTW it also works for the last day

$endOfCurrentMonth =  new \DateTime('last day of this month');

in case if month and year is geven than in order to find the first and end date of that month the following code will help


$date = ['y' => 2019, 'm' => 4];

 $monthStartDate = new \DateTime();
 $monthStartDate->setDate($date['y'], $date['m'], 1);

$monthEndDate = new \DateTime();
$monthEndDate->setDate($date['y'], $date['m'], 1);
$monthEndDate->modify('last day of this month');
add comment

Your Answer