Advertisement
Intermediate PHP, Date & Time Handling

How do you add or subtract a specific amount of time from a date using PHP's DateInterval and the modify or add methods?

Short answer

You can create a DateInterval object specifying a duration, such as three days or one month, and then use the DateTime object's add or sub method to shift a date forward or backward by that exact interval, or alternatively use the simpler modify method with a natural language…

Save PHP mock interview
Advertisement
AModel answer
You can create a DateInterval object specifying a duration, such as three days or one month, and then use the DateTime object's add or sub method to shift a date forward or backward by that exact interval, or alternatively use the simpler modify method with a natural language string, both approaches correctly handling tricky edge cases like month length differences and leap years automatically.
$date = new DateTime('2026-01-31');
$date->add(new DateInterval('P1M'));
echo $date->format('Y-m-d');
Real-world example
A subscription billing system calculates a customer's next billing date by adding a one month interval to their current billing date, correctly handling the transition from a thirty one day month into a shorter following month without any manual edge case handling.
Likely follow-ups
  • What does the DateInterval format string P1M actually mean?
  • What is the difference between using add with a DateInterval versus using the modify method?
Related topics