Richard
Richard

Reputation: 13

PHP Relative Date Issue

I have an issue with PHP relative dates, I have taken a look already at the aspect of relative dates vs. explicit dates. This seems to present when the first day in the month (in this case Monday) is the relative date needed. e.g. May 2017 and Jan 2018

I would expect the following to provide me with 1st May 2017, however, I get 8th May 2017 instead.

$var = new DateTime();
var_dump($var->modify('First Monday May 2017'));

/** Output **/
object(DateTime)#1 (3) {
  ["date"]=>  string(26) "2017-05-08 00:00:00.000000"
  ["timezone_type"]=>  int(3)
  ["timezone"]=> string(3) "UTC"
}

Thanks for your help.

Upvotes: 1

Views: 87

Answers (1)

Don't Panic
Don't Panic

Reputation: 41810

You need the of keyword.

$var = new DateTime();
var_dump($var->modify('first monday of May 2017'));

From the PHP documentation for relative formats:

Also observe that the "of" in "ordinal space dayname space 'of' " and "'last' space dayname space 'of' " does something special.
It sets the day-of-month to 1. "ordinal dayname 'of' " does not advance to another day. (Example: "first tuesday of july 2008" means "2008-07-01").

Upvotes: 5

Related Questions