Verification: a143cc29221c9be0

Php add days to day

add Method in DateTime() to Add Days in PHP

Using PHP version 5.3 and above, DateTime object and it’s add method can also be a solution. DateTime supports more date formats than strtotime and date. Using an object also easier than arbitrary functions. For example, when comparing two dates, it’s direct in DateTime, but in strtotime, converting the date first to timestamp is necessary.

Example:

add(new DateInterval('P1D')); // P1D means a period of 1 day
$fomattedDate = $date->format('Y-m-d');
?>

The following code will print output:

echo $fomattedDate; //output: 2020-02-28

The hard part of using DateTime() is the DateInterval object. This accepts a valid interval specification. The proper format starts with the letter P which means period, followed by an integer value, then D for the day. If the duration is time, the last part needs to be T.

Combination of Strtotime() and Date() to Add Days to Date in PHP

The strtotime() is a PHP function which is used to convert an English textual date description to a UNIX timestamp. The strtotime function will accept a string value that represents date-time.

Example:

The following code will output:

echo $date1; //output: 2020-02-28
echo $date2; //output: 2020-02-29

The above example will accept a date string with proper format and return the new date using strtotime and +1 days. date() function gave the proper format.

Note: To avoid obscurity, it’s recommended to use ISO 8601 (YYYY-MM-DD) format.

date_add() to Add Days to Date in PHP

This approach is the easiest among the others to add days, months, years, hours, minutes and seconds.

Example:

$oldDate = date_create("2020-02-27"); 
date_add($oldDate, date_interval_create_from_date_string("1 day"));

In application:

echo date_format($date,"Y-m-d"); //output: 2020-02-28

The above example also add dates to a date string, date_create() creates a DateTime object. date_interval_create_from_date_string() sets up a DateInterval from the parts of the string. Then finally, date_add() incrementes the date value.

Contribute

DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.