A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

PHP: Get start and end dates of a week from date(‘W’)

First off, from the PHP.net Manual, the ‘W’ inside the date() function returns the week number for a year.

Week
ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0)
Example: 42 (the 42nd week in the year)

A quick example of date(‘W’)

<?php
//October 29, 2009 is my birthday
echo date('W', strtotime('2009-10-29'));
//OUTPUT: 44
//October 29 is the 44th week in the year 2009

Here is the function to get the start and end dates given a week number:

function getWeekDates($year, $week, $start=true)
{
    $from = date("Y-m-d", strtotime("{$year}-W{$week}-1")); //Returns the date of monday in week
    $to = date("Y-m-d", strtotime("{$year}-W{$week}-7"));   //Returns the date of sunday in week
 
    if($start) {
        return $from;
    } else {
        return $to;
    }
    //return "Week {$week} in {$year} is from {$from} to {$to}.";
}

I did a couple of tests and so far the code worked okay. If you have a better way of doing it, post it below ;-)

PS: I got some of the code from a PHP.net comment and could no longer find the source. If you know the source, contact me.

This entry was posted in General and tagged , , , , . Bookmark the permalink.

4 Responses to PHP: Get start and end dates of a week from date(‘W’)

  1. ponbabitha says:

    it’s very useful for me
    thanks to every all

  2. Thanks ekini.net for providing me the code. It’s helped me to use for my project. Once again, thank you very much.

  3. BD says:

    if $week < 10, then
    $from = 1970-01-01
    and
    $to = 1970-01-01

  4. Paul Gardner says:

    The problem with weeks 1-9 is they are only 1 digit in length. Pad them with a leading zero and you’ll have more luck.

    When finding the solution to that problem I found the following page which suggests a simpler format for the strtotime command:

    http://derickrethans.nl/calculating-start-and-end-dates-of-a-week.html:

    For week 37 of year 2006

    Monday: strtotime("2006W37")
    Sunday: strtotime("2006W377")

    I tested the following and works fine:

    Monday: strtotime("2012W52")
    Sunday: strtotime("2012W527")

    Monday: strtotime("2013W01")
    Sunday: strtotime("2013W017")

    My code is:

    Monday: strtotime($year.'W'.str_pad($week, 2, 0, STR_PAD_LEFT))
    Sunday: strtotime($year.'W'.str_pad($week, 2, 0, STR_PAD_LEFT).'7')

    HTH, Paul.

Leave a Reply to ponbabitha Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>