PHP Date Exercises : Calculate weeks between two dates
Write a PHP script to calculate weeks between two dates.
Sample Solution:
PHP Code:
<?php
// Define a function to calculate the number of weeks between two dates
function week_between_two_dates($date1, $date2)
{
// Create DateTime objects from the input dates with the format 'm/d/Y'
$first = DateTime::createFromFormat('m/d/Y', $date1);
$second = DateTime::createFromFormat('m/d/Y', $date2);
// Swap the dates if the first date is greater than the second date
if($date1 > $date2) return week_between_two_dates($date2, $date1);
// Calculate the difference in days between the two dates and divide by 7 to get the number of weeks
return floor($first->diff($second)->days/7);
}
// Define the input dates
$dt1 = '1/1/2014';
$dt2 = '12/31/2014';
// Calculate and display the number of weeks between the two dates
echo 'Weeks between '.$dt1.' and '. $dt2. ' is '. week_between_two_dates($dt1, $dt2)."\n";
?>
Output:
Weeks between 1/1/2014 and 12/31/2014 is 52
Explanation:
In the exercise above,
- function week_between_two_dates($date1, $date2) { ... }: Defines a function named week_between_two_dates that takes two date strings as input parameters.
- $first = DateTime::createFromFormat('m/d/Y', $date1);: Creates a "DateTime" object from the first date string using the format 'm/d/Y'.
- $second = DateTime::createFromFormat('m/d/Y', $date2);: Creates a "DateTime" object from the second date string using the format 'm/d/Y'.
- if($date1 > $date2) return week_between_two_dates($date2, $date1);: Checks if the first date is greater than the second date and swaps them if necessary.
- return floor($first->diff($second)->days/7);: Calculates the difference in days between the two dates using the "diff()" method of the "DateTime" object, then divides the result by 7 and returns the floor value to get the number of weeks.
- Define input dates '$dt1' and '$dt2'.
- echo 'Weeks between '.$dt1.' and '. $dt2. ' is '. week_between_two_dates($dt1, $dt2)."\n";: Calls the "week_between_two_dates()" function with the input dates and prints the result.
Flowchart :
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a PHP script to calculate the current age of a person.
Next: Write a PHP script to get the number of the month before the current month.
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