Get Yesterday’s Date in PHP: Step-by-Step Guide

To get yesterday’s date in PHP, you can use the DateTime class along with the modify() method. Here’s a step-by-step guide on how to achieve this:

Step 1: Get the current date.

$current_date = new DateTime();

Step 2: Use the modify() method to move the DateTime object to yesterday.

$current_date->modify('-1 day');

Step 3: Format the updated DateTime object to get yesterday’s date in the desired format.

$yesterday_date = $current_date->format('Y-m-d');

Here’s the complete code in one block:

<?php
$current_date = new DateTime();
$current_date->modify('-1 day');
$yesterday_date = $current_date->format('Y-m-d');

echo "Yesterday's Date: " . $yesterday_date;
?>

The output will be yesterday’s date in the format “YYYY-MM-DD”.

For example, if today is '2023-05-25', the output will be:

Yesterday's Date: 2023-05-24

In this example, the modify() method with the argument '-1 day' moves the DateTime object to the previous day based on the current date. Then, the format() method is used to extract yesterday’s date in the desired format ('Y-m-d' represents the year, month, and day in the format “YYYY-MM-DD”).

You can modify the format() method to get yesterday’s date in a different format, depending on your specific requirements.