PHP date: One week ago.

This is a PHP guide on how to get a date was 7 days ago. Most of these examples are pretty easy to change, so you should be able to modify them to suit your own needs.

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

The above code outputted “2019-04-11” on the 18th of April, 2019.

If you want last week’s date to be displayed in a more human-friendly format, you can use the following example:

This will output a date such as “Thursday, 11th April, 2019”.

You can also get last week’s date by providing the strtotime function with “-1 week”:

Note that strtotime returns a UNIX timestamp. i.e. If you want the UNIX timestamp of last week’s date, you can just do the following:

This will output a timestamp such as “1554973963”.

Getting last week’s date with the DateTime object.

If you’re using PHP version 5.2 or above, you can utilize the Datetime functions:

In the example above, we used DateTime’s modify method to set the date back -7 days.

But what if you want to go one week back from a given date?

Here, we manually set the date to “2019-01-12” before subtracting 7 days. The output of this particular example is “2019-01-05” because that was a week before “2019-01-12”.

Hopefully, you found this tutorial useful!

Related:

Facebook Comments