← Back to Chapters

PHP Date_add, Date_sub & Date_modify

? PHP Date_add, Date_sub & Date_modify

? Quick Overview

The date_add(), date_sub(), and date_modify() functions in PHP are used to manipulate dates by adding, subtracting, or modifying time intervals on DateTime objects.

? Key Concepts

  • date_add() adds an interval to a DateTime object
  • date_sub() subtracts an interval from a DateTime object
  • date_modify() directly modifies the DateTime using readable strings

? Syntax & Theory

  • date_add(DateTime, DateInterval)
  • date_sub(DateTime, DateInterval)
  • date_modify(DateTime, string)

? Example 1: date_add()

? View Code Example
// Add 10 days to a specific date
<?php
$date = date_create("2025-12-25");
date_add($date, date_interval_create_from_date_string("10 days"));
echo date_format($date, "Y-m-d");
?>
Output: 2026-01-04

? Example 2: date_sub()

? View Code Example
// Subtract 10 days from a given date
<?php
$date = date_create("2025-12-25");
date_sub($date, date_interval_create_from_date_string("10 days"));
echo date_format($date, "Y-m-d");
?>
Output: 2025-12-15

? Example 3: date_modify()

? View Code Example
// Modify date using a human-readable interval
<?php
$date = date_create("2025-12-25");
date_modify($date, "+10 days");
echo date_format($date, "Y-m-d");
?>
Output: 2026-01-04

? Interactive Example

Click the button to see today’s date plus 7 days (JavaScript simulation):

Waiting...

? Use Cases

  • Subscription expiry calculation
  • Booking and scheduling systems
  • Report generation with future dates
  • Countdown and reminder features

✅ Tips & Best Practices

  • Use DateTime objects instead of raw timestamps
  • Prefer date_modify() for readable date logic
  • Always format output using date_format()

? Try It Yourself

  • Subtract 15 days from today’s date
  • Add 2 months using date_modify()
  • Change only the year of a DateTime object