PHP, strtotime and weeks over new year problems

Having problems with navigating over new year with weeks and think it's a bug? You are not alone, a friend of mine also thought so :-) There is a problem how to deal with starting days of week, Sunday or Monday causing the problem.

Problem: based on a date adding a week or 7 days (+1 week or +7 days) causing "20121224 +1week" end up on "20121231" if you set "Ymd" but if you go for "YW" you get "201201". If you instead use the ISO year "o" you will get the right year.

<?php
$start_date_period     
= "20121224";
$next_week_date         = date("Ymd", strtotime($start_date_period. " +1 week"));
$next_week_yearweek     = date("YW", strtotime($start_date_period. " +1 week"));
$next_week_ISO_yearweek = date("oW", strtotime($start_date_period. " +1 week"));


$next_week_date         => 20121231
$next_week_yearweek    
=> 201201
$next_week_ISO_yearweek
=> 201301
?>

Another good thing to know about is to be able to convert year-week and day into date format by using the ISO 8601 http://en.wikipedia.org/wiki/ISO_8601#Week_dates

<?php
 $test
= date('Ymd', strtotime("2013-W01-1")); //2013-W[week number]-[day number]
?>

http://www.php.net/manual/en/function.strtotime.php#105344

<?php
If you want the timestamp of the start of the ISO Week (i.e. on Monday) as defined by ISO 8601, you can use this one liner:
<?
php
$isoWeekStartTime
= strtotime(date('o-\\WW')); // {isoYear}-W{isoWeekNumber}
?>

?>
Knowledge keywords: