PHP: Subtract days from a date.

This is a tutorial on how to subtract days, weeks or months from a date using PHP. To do this, we can use either PHP’s strtotime function or the inbuilt DateTime class.

Yesterday / -1 days.

To get yesterday’s date, you can pass in the string “yesterday” to the strtotime function:

Passing in the string yesterday to strtotime is essentially the same thing as subtracting -1 days¬†from today’s date.

A DateTime alternative, which you can use if your PHP version is 5.3.0 or above:

The DateInterval class was introduced in PHP version 5.3.0 and its purpose is to represent a date interval. In the example above, we set the DateInterval object to P1D, which means a period of one day. We then subtracted that interval from the current date. If you wanted to subtract five days instead of one day, then you would use P5D instead of P1D.

If you want to subtract a day from a given date:

In the example above, we subtracted one day from 2019-01-01. This results in 2018-12-31.

One week ago / -7 days.

To get last week’s date in PHP, we can use the strtotime function like so:

In the example above, we passed “-7 days” in as a parameter to the strtotime function. This works because the strtotime function is pretty good at parsing textual date descriptions.

An example for those who prefer to use PHP’s DateTime class:

Above, we specified P1W as the $interval_spec parameter for DateInterval, which translates into “a period of one week.” If you want to subtract two weeks instead of one week, then change P1W to P2W.

Last month / -30 days.

Getting last month’s date can be a bit tricky. This is because the number of days in a month can vary. Example: October has 31 days, whereas September has 30 days.

Take the following example:

The snippet above will work in most situations. However, on the 31st of October, it will actually return the 1st of October. This is because PHP’s strtotime function treats “-1 month” the same as “-30 days.”

If you’re looking to get the previous month’s name or number, you might want to try the following code sample instead:

If you were to run the example above on the 31st of October, it should return the 1st of September.

As you can see, dealing with dates can be extremely tricky. Hopefully, the examples above helped you to better understand how to subtract from dates in PHP.

Related:

Facebook Comments