How to Determine the Dates in a Week Using PHP
The PHP "strtotime()" function can be used to determine the dates for each day of a given week number. The function is given a date format and changes that date into the current Unix timestamp ("now") or the timestamp for the given date and time. The Unix timestamp can then be changed back into an understandable date with the "date()" function. In PHP 5.1 and above, the "strtotime()" function uses the week number as part of the date format.
Instructions
-
-
1
Open a blank text document in any text editor.
-
2
Type the line "<?php" to start the PHP script.
-
-
3
Start the function with the following lines:
function week_to_date($year, $week)
{ -
4
Specify the time zone with the following line:
date_default_timezone_set('America/New_York');
This is required for PHP 5.1 and above.
-
5
Pad the week number with a 0 if the week number is below 10 with the following "if" statement:
if ($week <10){$week = "0".$week;}
This is needed for the "strtotime()" function.
-
6
Create the array that will hold the results with the following statement:
$dates=array();
-
7
Place the dates in the array with the following seven statements:
$dates['Sun'] = date("Y-m-d", strtotime("{$year}-W{$week}-0")); //Returns the date of Sunday in week
$dates['Mon'] = date("Y-m-d", strtotime("{$year}-W{$week}-1")); //Returns the date of Monday in week
$dates['Tue'] = date("Y-m-d", strtotime("{$year}-W{$week}-2")); //Returns the date of Tuesday in week
$dates['Wed'] = date("Y-m-d", strtotime("{$year}-W{$week}-3")); //Returns the date of Wednesday in week
$dates['Thu'] = date("Y-m-d", strtotime("{$year}-W{$week}-4")); //Returns the date of Thursday in week
$dates['Fri'] = date("Y-m-d", strtotime("{$year}-W{$week}-5")); //Returns the date of Friday in week
$dates['Sat'] = date("Y-m-d", strtotime("{$year}-W{$week}-6")); //Returns the date of Saturday in week -
8
End the function and return the dates.
return $dates;
}
Calling the Function
-
9
Create the variables that hold the week and year with the following two lines:
$year=2010;
$week=30; -
10
Call the function with the following line:
$results = week_to_date($year, $week);
-
11
Print the results with the following eight lines:
echo "The dates for week {$week} of {$year} are: <br />";
echo "Sunday: {$results['Sun']} <br />";
echo "Monday: {$results['Mon']} <br />";
echo "Tuesday: {$results['Tue']} <br />";
echo "Wednesday: {$results['Wed']} <br />";
echo "Thursday: {$results['Thu']} <br />";
echo "Friday: {$results['Fri']} <br />";
echo "Saturday: {$results['Sat']} <br />"; -
12
Type "?>" to end the PHP script.
-
1