time relative formats : get the date of the first Sunday of last year

Viewed 48

I want to retrieve the date of the first Sunday of last year, but i have a problem

$date = new DateTime('first sunday of august last year');

gives me as a result :

DateTime Object ( [date] => 2020-08-01 00:00:00.000000 [timezone_type] => 3 [timezone] => Europe/Berlin ) 
// saturday

but I want :

DateTime Object ( [date] => 2020-08-02 00:00:00.000000 [timezone_type] => 3 [timezone] => Europe/Berlin ) 
// sunday

is this a bug or am I at fault ?

2 Answers

It seem that last year fail to get the right date.

Seem confused between first sunday of august 2021 (08-01) and 2020 (08-02).

Using "hard coded" year, give the right date.

new DateTime('first sunday of august 2020', new DateTimeZone('Europe/Berlin'));
// "2020-08-02 00:00:00.000000"

A quick workaround could be :

$year = date('Y', strtotime('-1 year'));
$date = new DateTime('first sunday of august ' . $year, new DateTimeZone('Europe/Berlin'));
// "2020-08-02 00:00:00.000000"

The reason is

"ordinal dayname 'of' " does not advance to another day. (Example: "first wednesday of july 23rd, 2008" means "2008-07-02" because the specific phrase with 'of' resets the day-of-month to '1' and the '23rd' is ignored here).

You get the right answer if you specify the year:

$date = new DateTime('first sunday of august 2020');

Related