faqts : Computers : Programming : Languages : PHP : Function Libraries : Date and Time

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

5 of 12 people (42%) answered Yes
Recently 3 of 10 people (30%) answered Yes

Entry

How to get the dates if week number is given?

May 31st, 2006 10:39
Mike Shallop, Sanjana Alex,


If you assume that the week desired is in the current year, you can use
the following PHP script to reconstruct the first day of the week of the
target week.
The following assumptions are made:
1.  The first day of the week is Sunday - if you want to use Monday, you
will have to edit the code accordingly.
2.  You are not going back to the previous year.
3.  You want the beginning date of the 10th week of 2006.
Note that I am using an instance of a custom-written db-connect class to
connect and interact with MySQL - simply copy-pasting this code will not
work unless you incorporate a similar class with identical member
functions.  In other words, you'll have to author your own db-connect code.
The algorithm is as follows:
1. Calculate the current day of the week - Nth Day
2. Calculate the beginning date of the current week by subtracting N days
3. Calculate the current week of the year
4. Subtract the target week from the current week - Delta
5. Query the DB to render the date of the current date minus Delta weeks
<?php
	include("YOUR_DB_ACCESS_LIBRARY");
	$dbc = new YOURDB_OBJECT_CLASS();
	$weekday = date('w') ;
	$query = "SELECT DATE_ADD(CURDATE(), INTERVAL -$weekday DAY) AS week_start,
		          WEEK(DATE_ADD(CURDATE(), INTERVAL -$weekday DAY)) AS week_num";
	echo "<BR/>$query";
	$dbc->issue_query($query);
	if ($dbc->errno > 2)
		die($dbc->errstr);
	$line = $dbc->fetch_array();
	$weekstart = $line['week_start'];
	$weeknum = $line['week_num'];
	$targetweek = 10;   // hardcoded for example
	$startweek = bcsub($weeknum, $targetweek, 0);
	$query = "SELECT DATE_ADD('$weekstart', INTERVAL -$startweek WEEK) as
start_week";
	echo "<BR/>$query";
	$dbc->issue_query($query);
	if ($dbc->errno > 2)
		die($dbc->errstr);
	$line = $dbc->fetch_array();
	echo "<BR/>Week 10 begins on $line[start_week].";
?>
Given that the current date is 2006-05-31, the stub above generates the
following output:
SELECT DATE_ADD(CURDATE(), INTERVAL -3 DAY) AS week_start,
WEEK(DATE_ADD(CURDATE(), INTERVAL - 3 DAY)) AS week_num
SELECT DATE_ADD('2006-05-28', INTERVAL - 12 WEEK) as start_week
Week 10 begins on 2006-03-05.