Reputation: 35734
I am trying to use the php DateTime objects modify function to modify he date to a specific date in the month i.e. 10th or 20th etc.
I have tried all of the following, none of which work:
$d = new DateTime();
$d->modify('10th day');
$d->modify('10th');
$d->modify('10th of this month');
$d->modify('10th of the month');
Upvotes: 0
Views: 252
Reputation: 879
Try this:
$d = new DateTime('first day of this month');
$d->modify('+9 day');
PS: Nevertheless, I guess a better way to use
$cMonth = date('n');
$cYear = date('Y');
...
$d->setDate($cYear, $cMonth, 10);
Upvotes: 0
Reputation: 28891
Assuming you don't know the year and month (if you do, use DateTime::setDate()
), one way to do this would like this:
$day = 10; // 10th of the month
$dt = new DateTime('first day of this month');
$dt->modify('+' . ($day - 1) . ' days');
I have a feeling that there's also a way to do it strictly through the constructor, but like you, I couldn't figure out the magic string. Odd that "first day of the month" works, but "tenth day of the month" does not.
Edit: Apparently it's impossible to do this through the constructor. Even Rasmus suggests doing it this way instead.
Upvotes: 1
Reputation: 7096
You want to use DateTime::setDate
$date = new DateTime();
$date->setDate(2001, 2, 10);
Upvotes: 2