How to find the first day of current month in php

Ask a question+

I need to aggregate all data in a 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

$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?

add comment

1 Answer


I have found a lovely 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 given than 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');
Arthur Dilanyan 530
add comment

Your Answer