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:
//One week ago in a YYYY-MM-DD format. $lastWeek = date("Y-m-d", strtotime("-7 days")); echo $lastWeek, '<br>';
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:
$lastWeek = date("l, jS F, Y", strtotime("-7 days")); echo $lastWeek;
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:
//Get unix timestamp of last week. echo strtotime("-1 week");
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:
//Instantiate the DateTime object. $dateTime = new DateTime(); //Set the date to -7 days using the modify function. $dateTime->modify('-7 day'); //Print out the date in a YYYY-MM-DD format. echo $dateTime->format("Y-m-d");
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?
//Set a specific date. $dateTime = new DateTime('2019-01-12'); //Use modify method to go back -7 days from that date. $dateTime->modify('-7 day'); //Print out the date in a YYYY-MM-DD format. echo $dateTime->format("Y-m-d");
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!