w3resource

PHP Date Exercises : Add/subtract the number of days from a particular date


16. Date Arithmetic: Add/Subtract Days

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 :

Flowchart: Add/subtract the number of days from a particular date

For more Practice: Solve these Related Problems:

  • Write a PHP script to add a given number of days to a specified date using DateTime::modify() and display the new date.
  • Write a PHP function that subtracts a number of days from a date and outputs both the original and modified dates.
  • Write a PHP program to calculate the date 40 days before and after a given date, then print both results with labels.
  • Write a PHP script to compare a modified date with the current date and output the difference in days.

Go to:


PREV : Check if Date is a Weekend.
NEXT : Start and End Date of Week by Week Number.

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.