PHP Date Exercises : Start and end date of a week (by week number) of a particular year
Write a PHP function to get start and end date of a week (by week number) of a particular year.
Sample week and year : 12, 2014
Sample Solution:
PHP Code:
<?php
function Start_End_Date_of_a_week($week, $year)
{
$time = strtotime("1 January $year", time()); // Getting the timestamp for January 1st of the given year.
$day = date('w', $time); // Getting the numeric representation of the day of the week for January 1st.
$time += ((7*$week)+1-$day)*24*3600; // Calculating the timestamp for the starting day of the given week.
$dates[0] = date('Y-n-j', $time); // Formatting the starting date of the week.
$time += 6*24*3600; // Adding six days to get the timestamp for the end of the week.
$dates[1] = date('Y-n-j', $time); // Formatting the end date of the week.
return $dates; // Returning the array containing the starting and end dates of the week.
}
$result = Start_End_Date_of_a_week(12, 2014); // Calling the function to get the starting and end dates of the 12th week of 2014.
echo 'Starting date of the week: '. $result[0]."\n"; // Outputting the starting date of the week.
echo 'End date the week: '. $result[1]; // Outputting the end date of the week.
?>
Output:
Starting date of the week: 2014-3-24 End date the week: 2014-3-30
Explanation:
In the exercise above,
- function Start_End_Date_of_a_week($week, $year): Declaring a function named Start_End_Date_of_a_week which accepts two parameters: '$week' and '$year'.
- $time = strtotime("1 January $year", time());: Get the timestamp for January 1st of the given year.
- $day = date('w', $time);: Get the numerical representation of the day of the week for January 1st.
- $time += ((7*$week)+1-$day)*24*3600;: Calculates the timestamp for the starting day of the given week based on the given week number and year.
- $dates[0] = date('Y-n-j', $time);: Format the starting date of the week.
- $time += 6*24*3600;: Add six days to the timestamp to get the timestamp for the end of the week.
- $dates[1] = date('Y-n-j', $time);: Format the end date of the week.
- return $dates;: Returns the array containing the starting and end dates of the week.
- $result = Start_End_Date_of_a_week(12, 2014);: Calling the function to get the starting and end dates of the 12th week of 2014.
- echo 'Starting date of the week: '. $result[0]."\n";: Outputting the starting date of the week.
- echo 'End date the week: '. $result[1];: Outputs the end date of the week.
Flowchart :
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a PHP script to add/subtract the number of days from a particular date.
Next: Write a PHP script to calculate the current age of a person.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics