I need to be able to set a DateTime object to a certain day of the current month. I can obviously do this by getting the current month and creating a new DateTime, or checking the current day and creating a DateInterval object to modify the DateTime, but I want to just give plain text arguments to DateTime::modify.
I'm looking for something like:
$datetime->modify('10th day this month');
but this gives me an error like
PHP Warning: DateTime::modify(): Failed to parse time string (10th day this month) at position 0 (1): Unexpected character in php shell code on line 1
and I don't seem able to find the correct construction of the sentence to make PHP play nicely.
To get the first and last day of the current month, use the getFullYear() and getMonth() methods to get the current year and month and pass them to the Date() constructor to get an object representing the two dates.
php $query_date = '2010-02-04'; // First day of the month. echo date('Y-m-01', strtotime($query_date)); // Last day of the month. echo date('Y-m-t', strtotime($query_date));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With