I'm playing around with the PHP date relative formats and trying to get the 20th of the current month or 20th of the month of a given date.
I was hoping to use something like first day of this month +20 days
, but it still returns the first of the current month.
I know I could use the modify()
method twice, but I still hope there is a way to avoid this :-)
Am I doing something wrong or is it just not possible?
My Answer:
You can achieve the desired result by using the `last day of` format in combination with the `+X days` format. Here's an example code snippet to get the 20th of the current month or 20th of the month of a given date:
php
$currentDate = new DateTime();
$currentDate->modify('last day of this month');
$currentDate->modify('+20 days');
echo $currentDate->format('Y-m-d');
This code snippet first sets the date to the last day of the current month using the `last day of this month` format. Then, it adds 20 days to the date using the `+20 days` format to get the 20th of the current month.
You can also use a specific date instead of the current date by passing it to the `DateTime` constructor:
php
$givenDate = new DateTime('2022-03-15');
$givenDate->modify('last day of this month');
$givenDate->modify('+20 days');
echo $givenDate->format('Y-m-d');
This code snippet sets the given date to the last day of the month and then adds 20 days to get the 20th of the month of the given date.
I hope this helps! Let me know if you have any further questions.
Rate this post
4 of 5 based on 6849 votesComments