SyntaxStudy
Sign Up
PHP Date Differences & Intervals
PHP Intermediate 8 min read

Date Differences & Intervals

DateInterval represents a duration and is returned by DateTime::diff(). You can also construct intervals manually and add/subtract them from date objects.

  • $dt1->diff($dt2) returns a DateInterval.
  • DateInterval::createFromDateString() parses human strings.
  • DatePeriod iterates over a range of dates at a given interval.
Example
<?php
$start = new DateTimeImmutable('2000-01-01');
$end   = new DateTimeImmutable('2024-07-15');

$diff = $start->diff($end);

echo $diff->y . ' years';   // 24 years
echo $diff->m . ' months';  // 6 months
echo $diff->d . ' days';    // 14 days
echo $diff->days . ' total days'; // 8961 total days

// Invert flag: 1 means $end < $start
echo $diff->invert ? 'Past' : 'Future';

// Add / subtract a DateInterval
$interval  = new DateInterval('P1Y2M3D'); // 1 year, 2 months, 3 days
$future    = $start->add($interval);
$past      = $end->sub(new DateInterval('P30D')); // subtract 30 days

// DatePeriod — iterate every 7 days
$period = new DatePeriod(
    new DateTimeImmutable('2024-01-01'),
    new DateInterval('P7D'),  // weekly
    new DateTimeImmutable('2024-02-01')
);
foreach ($period as $date) {
    echo $date->format('Y-m-d') . "
";
}
Pro Tip

Tip: The DateInterval ISO 8601 duration format is P[n]Y[n]M[n]DT[n]H[n]M[n]S. The T separates the date part from the time part — e.g., PT30M means 30 minutes, not 30 months.