Friday, July 10, 2009

How to get week number for year, start date and end date for week

How to get week number for year, start date and end date for week based on date given or present date in php…..
The following function gives you the number of week in year based on the date given the date format is mm/dd/yyyy if your date format is in yyyy/mm/dd here is conversion of date in the required format or you can jump that conversion
The function gives you the following list
-number of week in year
- week date for particular week u selected
-week days for the week
-start date for a week
-end date for a week
-next week start date
-previous week end date
get_week('2010-01-31');//pass the date in the formate
function get_week($date)

{
    $main_date=explode("-",$date);
    $week_date = $main_date[1]."/".$main_date[2]."/".$main_date[0];

    $ts = strtotime($week_date);
    $year = date('Y', $ts);
    $week = date('W', $ts);
    // print week for the current date
    for($i=1; $i<=7; $i++)
    {
    // timestamp from ISO week date format
    $ts = strtotime($year.'W'.$week.$i);
    $week_dates[$i] = date("Y-m-d", $ts);
    $Week_days[$i] = date("l",$ts);  
    }
    //to get the week strat date and previous week last date
    $mon=explode("-" ,$week_dates[1]);
    $start_prev = date ("Y-m-d", mktime (0,0,0,date($mon[1]),(date($mon[2])),date($mon[0])));

    //to get the end date of the week next week start date
  
    $sun=explode("-", $week_dates[7]);
  
    $end_next = date ("Y-m-d", mktime (0,0,0,date($sun[1]),(date($sun[2])),date($sun[0])));
    echo $start_prev ."---".$end_next;
    //return array($start_prev ,$end_next);

}
?>

2 comments:

Anonymous said...

Teq guru has a useful information. its worth reading this blog.

there is a mistake in getting week start date and end date.
Plz fix this ASAP teq guru :)

Rakesh said...

thank you shridhar....n you have to give the date format as i mentioned above "yyyy-mm-dd'