ISO 8601 week number to date (timestamp) in PHP
47 Comments so far
Leave a comment
How do I convert an ISO 8601 week number to a timestamp or date?
Here’s a handy function for PHP that returns an array with seven timestamps, one for each day in week $weekNumber.
function getDaysInWeek ($weekNumber, $year) {
// Count from '0104' because January 4th is always in week 1
// (according to ISO 8601).
$time = strtotime($year . '0104 +' . ($weekNumber - 1)
. ' weeks');
// Get the time of the first day of the week
$mondayTime = strtotime('-' . (date('w', $time) - 1) . ' days',
$time);
// Get the times of days 0 -> 6
$dayTimes = array ();
for ($i = 0; $i < 7; ++$i) {
$dayTimes[] = strtotime('+' . $i . ' days', $mondayTime);
}
// Return timestamps for mon-sun.
return $dayTimes;
}
A simple way to test if it works:
$dayTimes = getDaysInWeek(33, 2006);
foreach ($dayTimes as $dayTime) {
echo (strftime('%a %Y%m%d', $dayTime) . "n");
}
I had some trouble with making this work on my local computer. A good guess is that this has something to do with my locales, so beware! Run the test on the computer that hosts your application before you rely on it.
47 Comments so far
Leave a comment
Leave a comment
Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
Thank you, just what I needed, good tip about using strtotime to make these calculations!
I had to change the string used by strtotime to “4 January 2006 + 33 weeks” to make it work for me, probably locale settings.
Comment by Rune August 16, 2006 @ 1:01 pmperfect. thank you very much.
Comment by safeen August 23, 2006 @ 11:44 amThis always works:
function getFirstDayOfWeek($year, $weeknr)
Comment by Patrick Nijs January 10, 2007 @ 2:48 pm{
$offset = date(‘w’, mktime(0,0,0,1,1,$year));
$offset = ($offset
Again, in valid HTML:
function getFirstDayOfWeek($year, $weeknr)
{
$offset = date(‘w’, mktime(0,0,0,1,1,$year));
$offset = ($offset < 5) ? 1-$offset : 8-$offset;
$monday = mktime(0,0,0,1,1+$offset,$year);
return strtotime(‘+’ . ($weeknr – 1) . ‘ weeks’, $monday);
Comment by Patrick Nijs January 10, 2007 @ 2:50 pm}
Brilliant!
Comment by Dandelion January 15, 2007 @ 11:18 pmWhat does Rune mean by “I had to change the string used by strtotime to “4 January 2006 + 33 weeks” to make it work for me, probably locale settings.”
Comment by Rajan August 2, 2007 @ 9:50 amThat instead of using:
$time = strtotime($year . '0104 +' . ($weekNumber - 1) . ' weeks');
He had to use:
Comment by tzzz August 2, 2007 @ 10:48 am$time = strtotime('4 January ' . $year . ' +' . ($weekNumber - 1) . ' weeks');
@Patrick Nijs… This is just what I was looking for! Thanks
Comment by batfastad October 10, 2007 @ 3:20 pmHere is another way to do it:
Comment by John December 31, 2007 @ 8:41 pm$date = date(‘m/d/Y’, strtotime(‘1 january 2007 + 33 weeks’));
Also,
$date = date(‘m/d/Y’, strtotime(‘2007W011′));
Where:
Comment by John December 31, 2007 @ 9:00 pm2007 = year
W01 = week one (W04 = week 4, etc)
1 = day of week to get date for (in this case, monday)
or u can try this function
function getDaysInWeek ($weekNumber, $year)
Comment by gigel January 23, 2008 @ 12:22 pm{
$date_object = date_create( “0 January $year” );
$date_object->modify( “+$weekNumber weeks” );
$dayTimes = $date_object->format( “d-m-Y” );
$date_object->modify( “-6 days” );
$dayTimes = $date_object->format( “d-m-Y” ).” – “.$dayTimes;
return $dayTimes;
}
KISS solution based on Johns entry:
/**
* Get the start of a given week (in this case monday is first day = W)
*
* @param integer $iWeekNumber
* @param string $sFormat
* @param integer $iYear
* @return mixed Datetime or UNIX time depending on format
*/
public static function getDatetimeWeekStart( $iWeekNumber, $iYear = null, $sFormat = ‘d\.m\.Y’)
{
if ( is_null($iYear) ) $iYear = date(“Y”);
if ( $iWeekNumber < 10 ) $iWeekNumber = “0″.$iWeekNumber;
$iTime = strtotime($iYear.’W’.$iWeekNumber);
return date($sFormat, $iTime);
}
Example this week:
print getDatetimeWeekStart(date(‘W’));
Example week 10 in 2006:
print getDatetimeWeekStart(10, 2006);
Example week 52 in 2009 in unixtime:
print getDatetimeWeekStart(52, 2009, ‘U’);
Best regards
Comment by HorsMark March 14, 2008 @ 9:06 amJesper HorsMark
[...] return $dayTimes; } aus: ISO 8601 week number to date (timestamp) in PHP Er gibt dir einen Array mit 7 Eintrgen zurck, fr jeden Tag einen. Davon brauchst du eben nur [...]
Pingback by Erster Tag einer Woche - PHP @ tutorials.de: Forum, Tutorial, Anleitung, Schulung & Hilfe April 4, 2008 @ 12:26 pmPatrick Nijs’s code does not work every time. For example, year 2008, week number 1
Comment by Jasmo July 28, 2008 @ 11:54 amWeek 1 starts in last year, 31.12.2007 to be exact. Patrick’s code does not understand that and says that first day of the first week is 1.1.2008.
Very useful for me, just what i wanted.
Comment by centerax September 15, 2008 @ 9:29 pmThanks!
[...] So, i searched on google and found this as first result: http://tzzz.wordpress.com/2006/08/14/8/ [...]
Pingback by Get timestamps out of week no. and year. | Rene's PHP Blog October 23, 2008 @ 10:49 amThanks for the code! It was very usefull.
I posted someting on my blog to show you how i used it. And a backlink to this blogpost!
Comment by Rene October 23, 2008 @ 10:52 amI think he made mistakes in finding the $mondayTime
You can test that with week 52 year 2008 and week 1 year 2009.
This is the revised code:
function getDaysInWeek ($weekNumber, $year) {
Comment by nkonx October 29, 2008 @ 9:41 am// Count from ‘0104′ because January 4th is always in week 1
// (according to ISO 8601).
$time = strtotime($year . ‘0104 +’ . ($weekNumber – 1)
. ‘ weeks’);
// Get the time of the first day of the week
$diff = (date(‘w’, $time) – 1 >= 0) ? (date(‘w’, $time) – 1) : 6;
$mondayTime = strtotime(‘-’ . $diff . ‘ days’, $time);
// Get the times of days 0 -> 6
$dayTimes = array ();
for ($i = 0; $i < 7; ++$i) {
$dayTimes[] = strtotime(‘+’ . $i . ‘ days’, $mondayTime);
}
// Return timestamps for mon-sun.
return $dayTimes;
}
Also for week 53 year 2009 and week 1 year 2010…
Comment by nkonx October 29, 2008 @ 9:46 amHere is a function for finding the number of weeks in a year:
function datetime_nweek_in_year($year) {
Comment by nkonx October 29, 2008 @ 9:47 am// Count from ‘1228′ because December 28th is always in last week
// (according to ISO 8601).
$n = intval(date(‘W’, strtotime($year.’1228′)));
return $n;
}
function week2date($year, $week, $weekday=7) {
Comment by Ramsed November 21, 2008 @ 9:53 pm$time = mktime(0, 0, 0, 1, (4 + ($week-1)*7), $year);
$this_weekday = date(“N”, $time);
return mktime(0, 0, 0, 1, (4 + ($week-1) * 7 + ($weekday – $this_weekday)), $year);
}
I would be so happy if anyone could help me.
This scripts belives that there’s 53 weeks in year 2008
it’s only 52 ofc. så week 1 in 2009 is week 2 IRL.
and week 2 is week 3 and so on. Why does this occur? i’ve tryed to solve it. but i cant :’(
PLEASE!! COntact me @ patrik@quick-bemanning.se
Comment by Patrik December 13, 2008 @ 3:12 amI would be so greatfull for any solution!
Loved this, thans a lot
.
Comment by Severo December 23, 2008 @ 6:58 pmFixed the years with 29 february
Comment by Juan Guzman December 30, 2008 @ 4:53 pmif (($year -1)/ 4 == intval(($year -1)/ 4)) $time = $time – 172800;
Leap year fix in previous comment unfortunately doesn’t really work in my script … I did, however, manage to fix the problem temporarily by writing ‘1 January’ instead of ‘4 January’. Will be re-set again for 2010 and following years. thx!
Comment by ahhoi January 2, 2009 @ 9:35 pmI’ve try this script and for unfortunately concidence, this year the 20090104 is sunday.
Comment by Alessandro bellisai January 6, 2009 @ 12:17 amSo the script fail to calculate $mondayTime = strtotime(‘– 1 days’, $time); don’t work!
This is the fix
if ((date(“w”, $time) == 0))
{
$mondayTime = strtotime(“-6 days”, $time);
}
else
{
$mondayTime = strtotime(“-” . (date(“w”, $time) – 1) . ” days”, $time);
}
John’s solutions (and thus HorsMark’s KISS one) won’t work because
Comment by Janis March 23, 2009 @ 9:24 am1) in the first case it won’t be the Monday of the given week;
2) the second case needs ISO weeknumber year for the input not the usual Gregorian year (which is the case).
I think nobody noticed one mistake in the code…
$mondayTime = strtotime(‘-’ . (date(‘w’, $time) – 1) . ‘ days’, $time);
Which is totally wrong, according to PHP.net. If we handle weeks in ISO 8601 format, we have to do the same, according to days, arn’t we?
We have to use date(‘N’) to handle days in ISO format, instead of date(‘w’)…
So it should be:
$mondayTime = strtotime(‘-’ . (date(‘N’, $time) – 1) . ‘ days’, $time);
Comment by DjZoNe July 3, 2009 @ 12:42 pmЦюрих – культурный центр ШвейцарииПредставляем вашему вниманию Цюрих – самый крупный экономический и культурный центр Швейцарии, и в тоже время, благодаря исключительному единению местоположения и архитектуры, один из самых замечательных городов Европы.
Comment by Адам September 26, 2009 @ 9:25 amИнтересные автомобильные новости про элитные внедорожники из Европы и родстеры Audi, актуальные статьи и заметки про купе Mercedes и Porshe. Широкий выбор информации про автотюнинг, седаны Cadillac и cпорткары Lamborghini.
Comment by Захария September 30, 2009 @ 9:01 pmСтудия оптимизации SEO-Магия: Оптимизация сайтов, Продвижение сайтов, Написание текстов статей, Аудит сайтов, Регистрация в каталогах, SEO-консультации, SEO-копирайтинг, Мониторинг позиций, а также поддержка сайтов!
Comment by Антон October 3, 2009 @ 8:55 amЭстетик-клубСалон красоты “Эстетик-клуб” – это полный спектр парикмахерских услуг, эксклюзивная косметология, салон массажных техник, спа-салон, коррекция фигуры, маникюр и педикюр, салон для загара, салон будущих мам, мужской салон. Наш телефон (812) 590 85 66. Рады видеть вас ежедневно с 10 до 21.
Comment by Марк October 5, 2009 @ 5:52 pmCmyguo – раскрутка сайтов бесплатно: раскрутка, реклама сайтовОдна из наших основных специализаций – раскрутка сайта бесплатно, раскрутка, оптимизация сайтов, реклама сайтов, продвижение сайтов
Comment by Юрий October 7, 2009 @ 3:07 pmDrevstroy: колун, тачка садовая, кувалда, лампа керосиноваяМы предлагаем максимальные скидки на товары собственного производства – У нас есть: тачка садовая, веник сорго, лампа керосиновая
Comment by Юрий October 16, 2009 @ 7:59 pmЭкомстат: мешок для мусора, бигудиМы работаем на российском рынке более четырнадцати лет. В нашем арсенале: вешалки, полиэтиленовая пленка, мешки для мусора и многое другое.
Comment by Юрий October 18, 2009 @ 2:48 amMБ-Торг: люминесцентная лампа, дрл, лампы накаливания, прожекторыМы предлагаем нашим клиентам широкий спектр изделий: светильники ЛПО, светильники РКУ, ЖКУ, лампы накаливания
Comment by Юрий October 20, 2009 @ 3:07 pmНаша красотка – русская красавица.
Comment by Наша красотка October 21, 2009 @ 11:51 amВсе для нас, дорогие женщины!
Game-Fox.Ru: Скачать игры PC, шаблоны, патчи, иконки, шапки, трейнеры, быстро, бесплатно и без регистрации!
Comment by Антон October 26, 2009 @ 12:08 pmКупить светильники бра: Vian 7100/AP2 CP, Vian 4900/AP1, Vian 5900/AP1 CP, Sylcom 202/A2, Baga 1121, а также потолочные светильники: Bolero Pl75, Baga 2182, Queen, Pascale PL, Elysee, Faustig 71045, BRS, Faustig 70906, Emme Pi Light 8020, Busato 003-16C.
Comment by Евгений October 28, 2009 @ 11:45 amКупить светильники бра: Vian 7100/AP2 CP, Vian 4900/AP1, Vian 5900/AP1 CP, Sylcom 202/A2, Baga 1121, а также потолочные светильники: Bolero Pl75, Baga 2182, Queen, Faustig 71045, Elysee, Pascale PL, BRS, Emme Pi Light 8020, Faustig 70906, Busato 003-16C.
Comment by Евгений October 28, 2009 @ 3:40 pmКупить светильники бра: Vian 7100/AP2 CP, Vian 4900/AP1, Vian 5900/AP1 CP, Sylcom 202/A2, Baga 1121, а также потолочные светильники: Baga 2182, Bolero Pl75, Queen, Pascale PL, BRS, Elysee, Faustig 71045, Faustig 70906, Emme Pi Light 8020, Busato 003-16C.
Comment by Евгений October 29, 2009 @ 12:19 pmСайт компании ООО “Сладкая жизнь”, одной из самых крупнейших компаний, специализирующихся на производстве пирожных. Компания выпускает больше 50 видов тортовых изделий , выделяющихся по своему вкусовым качествамиразмерами. Особенно стоит отметить разнообразие и изысканность внешнего оформления тортов.
Comment by Азалия November 19, 2009 @ 9:40 amЗаинтересовала ваша статья. Если Вы не против могу дать вам пару советов. Немного украсте дизайн Вашего сайта, а также проведите seo продвижение, чтоб больше посетителей было. Если заинтересовало поможем трафиком
Comment by seowqa November 20, 2009 @ 4:43 amСветильники распродажа магазин, Москва. Люстры торшеры подвесы.Люстры в стиле Tiffany магазин, Москва. Бра торшеры лампы подвесы люстры. Светодизайн. Кухонные лампы.
Comment by Евдоким November 22, 2009 @ 12:40 amСветильники уличные. Бра люстры продажа, магазин света в Москве.Где купить люстры, лампы, торшеры, светильники. Купить настенные лампы светильники, настенно-потолочные светильники можно здесь. Светильники напольные декоративные.
Comment by Михаил November 23, 2009 @ 3:31 amФильмы онлайн: мелодрамы, трейлеры, бесплатно.Скачать фильмы: мелодрамы, фентези, драмы, фантастика, приключения, ужасы, боевики, трейлеры, мультфильмы, комедии, триллеры, документальные фильмы.
Comment by Антон November 28, 2009 @ 12:44 pmНа сайте Вы отыщите огромное количество красивейших обоев для десктопа вашего компьютера. Тысячи обоев ждут, когда Вы скачаете их и разместите на Ваш рабочий стол. Будьте уверенны они отдадут Вам замечательно настроение и скрасят будни перед компьютером. Заходите, качайте, размещайте, наслаждайтесь.
Comment by Элла November 30, 2009 @ 12:04 pm