Subtract Year from Date in PHP: Step-by-Step Guide with Example

To subtract a year from a date in PHP, you can use the DateTime class along with the modify() method. Here’s a step-by-step example of how to achieve this:

Step 1: Create a DateTime object with the initial date.

$initial_date = new DateTime('2023-05-25'); // Replace this with your initial date

Step 2: Define the number of years you want to subtract from the initial date.

$years_to_subtract = 1; // Replace this with the number of years to subtract

Step 3: Use the modify() method to subtract the years from the DateTime object.

$modified_date = $initial_date->modify('-' . $years_to_subtract . ' year');

Step 4: Format the modified DateTime object to display the result in the desired format.

$result_date = $modified_date->format('Y-m-d');

Here’s the complete code in one block:

<?php
$initial_date = new DateTime('2023-05-25'); // Replace this with your initial date
$years_to_subtract = 1; // Replace this with the number of years to subtract
$modified_date = $initial_date->modify('-' . $years_to_subtract . ' year');
$result_date = $modified_date->format('Y-m-d');

echo "Result Date: " . $result_date;
?>

The output will be the date with the specified number of years subtracted from the initial date.

For example, if you want to subtract 1 year from the date, the output will be:

Result Date: 2022-05-25

In this example, we use the modify() method with a string that represents the number of years to be subtracted ('-' . $years_to_subtract . ' year'). The modified DateTime object is then formatted to display the result 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 the result date in a different format, depending on your specific requirements.