Calculate last day of month with PHP and DateTime

Calculate last day of month with PHP and DateTime

There are multiple options to calculate a the last (or first) day of a month. The most readable I found is the following for the current month:

$lastDayOfCurrentMonth = new \DateTime('last day of this month');
$firstDayOfCurrentMonth = new \DateTime('first day of this month');

We only need to update that slightly to get the same result for any month:

$today = new \DateTime();

$lastDayOfMonth = new \DateTime(sprintf('last day of %s', $today->format('Y-m')));

The same goes for the first of the month:

$today = new \DateTime();

$firstDayOfMonth = new \DateTime(sprintf('first day of %s', $today->format('Y-m')));