How do I target a specific day of the current month with DateTime::modify?

It isn't possible to get the Xth day of a given month directly, but you can achieve this with a simple workaround:

$datetime->modify('last day of previous month')->modify('+10 day');

Another alternative would be:

$datetime->format('Y-m-10');

If you must use DateTime::modify() then this workaround may suit you:-

$date = new \DateTime();
$date->modify($date->format('Y-m-10'));

Although it probably isn't any better than Amal's answer, I offer it here just as an alternative that avoids the double call.

Demo


I found this saves a few microseconds to use setDate() and format() to extract the current year and month to satisfy setDate's 3 arguments (but kinda verbose)

$date = new \DateTime();
$date->setDate($date->format('Y'), $date->format('m'), 10);

Tags:

Datetime

Php