date_add() ~ How To Add Days, Months and Years in a Custom Date in PHP?

Php gives a function for calculating days, months and years on a custom date. The method is date_add().

You can add days or months or years to a date in round figure.

Table of Contents
|| Add days to a date in PHP in round figure
|| Add months to a date
|| Add years to a date
|| Add weeks to a date
|| Add days, months and year together

The first parameter we use in the date_add() function is our created custom date. Read this article to know how to create a custom date.

And, in the second parameter an another function which is date_interval_create_from_date_string(). This function is too long. You can give value in its argument like this to add those in the round figure in custom date-

  • 5 days
  • 7 months
  • 4 years

The date_add() method returns an object.

Before getting the result, you need to define the format of the final date. So access format() method from the object.

add days to a date in PHP

<?php

$date = date_create("30-03-2020");
$add_days = date_add($date,date_interval_create_from_date_string("5 days"));
$date_format = $add_days->format("d-m-Y");

echo $date_format;

?>

add months to a date in PHP

<?php

$date = date_create("30-03-2020");
$add_months = date_add($date,date_interval_create_from_date_string("10 months"));
$date_format = $add_months->format("d-m-Y");

echo $date_format;

?>

add years to a date in PHP

<?php

$date = date_create("30-03-2020");
$add_years = date_add($date,date_interval_create_from_date_string("3 years"));
$date_format = $add_years->format("d-m-Y");

echo $date_format;

?>

Add 3 days 6 months 2 years to a date in PHP

<?php

$date = date_create("30-3-2020");
$add_date = date_add($date,date_interval_create_from_date_string("3 days 6 months 2 years"));
$date_format = $add_date->format("d-m-Y");
echo $date_format;

?>

Add weeks to a date

<?php

$date = date_create("30-3-2020");
$add_weeks = date_add($date,date_interval_create_from_date_string("2 weeks"));
$date_format = $add_weeks->format("d-m-Y");
echo $date_format;

?>
Related Posts
** Create a custom date in PHP
** Get current date in PHP
** Know the differences between two dates
** How to print all months of gregorian calendar in PHP using a loop
** Number of days in a month in PHP

Leave a Comment