Erik Brickarp
Erik Brickarp

Reputation: 48

DateTime, +1 week and -1 week not working the same

I have a couple of functions juggling back and forth with weeks.

One surprising, and unwanted, behavior I discovered was this:

$date = new DateTime();
$date->setISODate(2014, 52);
$date->modify('+1 week');
echo date('YW', $date->getTimestamp()) . '<br />';

$date->setISODate(2014, 01);
$date->modify('-1 week');
echo date('YW', $date->getTimestamp()) . '<br />';

This code prints:
201401
201352

My expectation was:
201501
201352

Three questions:

1) Have I done something wrong in the code above or is there an inconsistent behavior between "+1 week" and "-1 week" (as in year not being stepped in the first case)?

Answer from comment:
It never increase/decrease year but week 1 happens to start in December 2013 thus it seems like it decrease year in the "-1 week" example.

2) If there is an inconsistency, can I trust the code will work the same on various platforms and PHP versions?

Answer:
No inconsistency (see accepted answer)

3) Is there a better way to step 1 week backward and forward in time (input is year and week, output is also year and week)?

bonus question) If there actually is an inconsistency, does anyone know why?

Answer:
No inconsistency, see answer on number 1 for explanation

Upvotes: 2

Views: 208

Answers (1)

Artur
Artur

Reputation: 384

  • Y is year from the date
  • o is ISO-8601 year number
  • W is ISO-8601 week number of year

if using 'W' for the week number use 'o' for the year.

Upvotes: 5

Related Questions