How to add or subtract days, months, or years from a DateTime object in PHP?

In PHP, you can use the DateTime class to add or subtract days, months, or years from a DateTime object using the modify() method. Here's an example:

$date = new DateTime(); // Create a new DateTime object // Add 5 days $date->modify('+5 days'); // Subtract 1 month $date->modify('-1 month'); // Add 2 years $date->modify('+2 years'); // Output the modified date echo $date->format('Y-m-d');

In the modify() method, you can specify the number of days, months, or years you want to add or subtract by using a date/time interval format.

Some examples:

  • +5 days adds 5 days.
  • -1 month subtracts 1 month.
  • +2 years adds 2 years.

You can modify the DateTime object multiple times by calling the modify() method multiple times.