PHP Date Exercises : Add/subtract the number of days from a particular date
PHP date: Exercise-16 with Solution
Write a PHP script to add/subtract the number of days from a particular date.
Sample Solution:
PHP Code:
<?php
$dt='2011-01-01'; // Assigning the date '2011-01-01' to the variable $dt.
echo 'Original date : '.$dt."\n"; // Outputting the original date.
$no_days = 40; // Setting the number of days to 40.
$bdate = strtotime("-".$no_days." days", strtotime($dt)); // Subtracting 40 days from the original date using strtotime function and storing the result in $bdate.
$adate = strtotime("+".$no_days." days", strtotime($dt)); // Adding 40 days to the original date using strtotime function and storing the result in $adate.
echo 'Before 40 days : '.date("Y-m-d", $bdate)."\n"; // Outputting the date 40 days before the original date.
echo 'After 40 days : '.date("Y-m-d", $adate)."\n"; // Outputting the date 40 days after the original date.
?>
Output:
Original date : 2011-01-01 Before 40 days : 2010-11-22 After 40 days : 2011-02-10
Explanation:
In the exercise above,
- $dt='2011-01-01': Assign the date '2011-01-01' to the variable '$dt'.
- echo 'Original date : '.$dt."\n";: Outputting the original date stored in '$dt'.
- $no_days = the variable '$no_days' to 40.
- $bdate = strtotime("-".$no_days." days", strtotime($dt));: Subtracting 40 days from the original date using "strtotime()" function and storing the result in '$bdate'.
- $adate = strtotime("+".$no_days." days", strtotime($dt));: Adding 40 days to the original date using "strtotime()" function and storing the result in '$adate'.
- echo 'Before 40 days : '.date("Y-m-d", $bdate)."\n";: Outputting the date 40 days before the original date.
- echo 'After 40 days : '.date("Y-m-d", $adate)."\n";: Outputting the date 40 days after the original date.
Flowchart :
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a PHP script to check if a date is a weekend or not.
Next: Write a PHP function to get start and end date of a week (by week number) of a particular year.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/php-exercises/php-date-exercise-16.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics