PHP: Add days to a date.

This is a short tutorial on how to add days to a given date using PHP. To do this, we can either use a combination of date and strtotime or we can take the OO approach and use the DateTime class.

Using the DateTime class to add days to a date.

Let’s start off by looking at a few examples using the DateTime class.

Adding 30 days to a date.

In the following example, I will add 30 days to a given date:

In the code above:

  1. We created a new DateTime object and passed in the date that we want to add days onto. In this case, I used the 10th of June, 2019. i.e. We want to add 30 days onto the 10th of June, 2019.
  2. We then created a DateInterval object and set the $interval_spec parameter in the constructor to P30D. P30D stands for “a period of 30 days.”
  3. Afterwards, we added this DateInterval to our DateTime object using the add function.
  4. Finally, we printed out the result using the DateTime::format function.

Add 7 days to a date using DateTime.

The PHP snippet above can be easily modified to add 7 days instead of 30. The only thing that needs changing is the line where we instantiated the DateInterval class:

Adding days to today’s date.

If you want to add days to today’s date, then you can simply omit the parameter in the constructor:

The DateTime object above will default to the current timestamp.

Other DateInterval examples.

Here are a few other interval specifications that can be used with the DateInterval class:

  • P1Y: Adds a period of one year.
  • P5D: Adds a period of 5 days.
  • P1D: Adds a period 1 day.
  • P6M: Adds a period of 6 months.
  • P4W: Adds a period of 4 weeks.

As of PHP version 7.1, you can even add microseconds onto a timestamp.

Using date and strtotime.

If you feel more comfortable using the date and strtotime functions, then you can use the following example:

In the code above, we added 30 days onto the current date.

However, if you are wanting to add days to a given date, then you will need to modify your approach a little:

As you can see, the strtotime function is actually pretty useful in the sense that you can almost write exactly what you want in plain English into the first parameter. For example, you can also tell it to add one month:

Hopefully, you found this guide useful!

Related: PHP: One week ago.

Facebook Comments