Skip to content
Advertisement

Getting first / last date of the week

Is it possible to get the first / last date of a week using PHP’s Relative Date Time format?

I’ve tried to do:

date_default_timezone_set('Europe/Amsterdam');
$date = new DateTime();

$date->modify('first day of this week'); // to get the current week's first date
echo $date->format('Y-m-d'); // outputs 2011-12-19

$date->modify('first day of week 50'); // to get the first date of any week by weeknumber
echo $date->format('Y-m-d'); // outputs 2011-12-18

$date->modify('last day of this week'); // to get the current week's last date
echo $date->format('Y-m-d'); // outputs 2011-12-17

$date->modify('last day of week 50'); // to get the last date of any week by weeknumber
echo $date->format('Y-m-d'); // outputs 2011-12-18

As you can see it doesn’t output the correct dates.

According to the docs this should be possible if I’m correct.

Am I doing something terrible wrong?

EDIT

I need to use PHP’s DateTime for dates in the far future.

UPDATE

It gets only stranger now. I’ve done some more testing.

Windows PHP 5.3.3

2011-12-01

Warning: DateTime::modify() [datetime.modify]: Failed to parse time string (first day of week 50) at position 13 (w): The timezone could not be found in the database in C:UsersGerrieDesktopphWebsitesChartswww.charts.compublicindex.php on line 9
2011-12-01
2011-11-30

Warning: DateTime::modify() [datetime.modify]: Failed to parse time string (last day of week 50) at position 12 (w): The timezone could not be found in the database in C:UsersGerrieDesktopphWebsitesChartswww.charts.compublicindex.php on line 15
2011-11-30

Linux 5.3.8

2011-12-01
2011-12-01
2011-11-30
2011-11-30

Advertisement

Answer

According to docs the format strings “first day of” and “last day of” are only allowed for months, not for weeks. See http://www.php.net/manual/en/datetime.formats.relative.php

If you combine first and last day of with a week statement the result either blows the parser or is something that you did not expect (usually the first or last day of a month, not a week).

The difference that you see between Win and Linux is probably only because of different error reporting settings.

To get the first and last day of the current week use:

$date->modify('this week');
$date->modify('this week +6 days');

To get the first and last day of week 50 use:

$date->setISODate(2011, 50);
$date->setISODate(2011, 50, 7);

EDIT:

If you want to use the modify method for absolute week numbers you have to use the formats defined in http://www.php.net/manual/en/datetime.formats.compound.php:

$date->modify('2011W50');
$date->modify('2011W50 +6 days');
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement