Date Arithmetic with DateInterval
Add and subtract time periods using DateInterval and modify().
Date Arithmetic with DateInterval is a free PHP Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
DateInterval Overview
DateInterval represents a duration of time — days, months, hours, etc. It's the PHP OO way to add or subtract time from DateTime objects.
Creating DateInterval
Create a DateInterval using ISO 8601 duration notation:
<?php
// P = period, T = time separator
$oneYear = new DateInterval('P1Y'); // 1 year
$sixMonths = new DateInterval('P6M'); // 6 months
$tenDays = new DateInterval('P10D'); // 10 days
$twoHours = new DateInterval('PT2H'); // 2 hours (T before time)
$complex = new DateInterval('P1Y2M3DT4H5M6S');
echo $oneYear->y; // 1
echo $tenDays->d; // 10add() and sub()
Add or subtract a DateInterval from a DateTime:
<?php
$dt = new DateTime('2024-01-01');
$dt->add(new DateInterval('P1Y')); // +1 year
echo $dt->format('Y-m-d'); // 2025-01-01
$dt->sub(new DateInterval('P3M')); // -3 months
echo $dt->format('Y-m-d'); // 2024-10-01diff() Between Two Dates
diff() returns a DateInterval representing the difference between two dates:
<?php
$start = new DateTime('2024-01-01');
$end = new DateTime('2024-06-15');
$diff = $start->diff($end);
echo $diff->y; // years
echo $diff->m; // months
echo $diff->d; // days
echo $diff->h; // hours
echo $diff->days; // total days: 166Human-Readable Differences
Format a DateInterval for display:
<?php
$birthdate = new DateTime('1990-05-15');
$today = new DateTime();
$age = $birthdate->diff($today);
echo $age->y . ' years, ' . $age->m . ' months, ' . $age->d . ' days';
// Check if date is in the past
if ($diff->invert === 1) {
echo 'Date was in the past';
}DateInterval::createFromDateString()
Create a DateInterval from a natural language string:
<?php
$interval = DateInterval::createFromDateString('1 year 2 months 3 days');
$dt = new DateTime('2024-01-01');
$dt->add($interval);
echo $dt->format('Y-m-d'); // 2025-03-04
// Other examples:
DateInterval::createFromDateString('next monday');
DateInterval::createFromDateString('6 weeks');DatePeriod — Iterate Over Ranges
DatePeriod lets you iterate over a date range at regular intervals:
<?php
$start = new DateTime('2024-01-01');
$interval = new DateInterval('P1M'); // monthly
$end = new DateTime('2024-06-01');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $date) {
echo $date->format('Y-m') . PHP_EOL;
}
// 2024-01, 2024-02, 2024-03, 2024-04, 2024-05Using DatePeriod for Weekly Reports
Generate weekly date checkpoints:
<?php
$start = new DateTime('2024-01-01');
$interval = new DateInterval('P7D'); // weekly
$end = new DateTime('2024-02-01');
$weeks = new DatePeriod($start, $interval, $end);
foreach ($weeks as $week) {
echo 'Week of: ' . $week->format('Y-m-d') . PHP_EOL;
}Comparing Intervals
Compare the magnitude of two DateIntervals by converting to total days:
<?php
$a = new DateTime('2024-01-01');
$b = new DateTime('2024-06-01');
$c = new DateTime('2025-01-01');
$diff1 = $a->diff($b)->days; // 152
$diff2 = $a->diff($c)->days; // 366
echo ($diff1 < $diff2) ? 'First interval shorter' : 'First interval longer';
// First interval shorterBusiness Days Calculation
Calculate the number of business days between two dates:
<?php
function businessDays(DateTime $from, DateTime $to): int {
$count = 0;
$cur = clone $from;
while ($cur < $to) {
$dow = (int) $cur->format('N'); // 1=Mon ... 7=Sun
if ($dow < 6) $count++;
$cur->modify('+1 day');
}
return $count;
}
$from = new DateTime('2024-05-27');
$to = new DateTime('2024-06-07');
echo businessDays($from, $to) . ' business days';Expiry Date Pattern
Common subscription/token expiry pattern using DateInterval:
<?php
function expiresAt(string $duration = 'P30D'): string {
$dt = new DateTimeImmutable();
return $dt->add(new DateInterval($duration))->format('Y-m-d H:i:s');
}
echo expiresAt('P30D'); // 30-day trial expiry
echo expiresAt('P1Y'); // 1-year subscription expiry
echo expiresAt('PT1H'); // 1-hour token expiryQuick Check
What does $dateA->diff($dateB)->days return?
Recap: DateInterval
Key points:
new DateInterval('P1Y2M3DT4H')— ISO 8601 durationadd()/sub()to modify DateTimediff()returns DateInterval between two datesDatePerioditerates over a date range- Use
->daysfor total day count from diff() - Check
->invertto know if interval is negative
Frequently asked questions
Is the “Date Arithmetic with DateInterval” lesson free?
Yes — the full text of “Date Arithmetic with DateInterval” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.
What will I learn in “Date Arithmetic with DateInterval”?
Add and subtract time periods using DateInterval and modify(). You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start PHP Academy?
No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Date Arithmetic with DateInterval” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this PHP Academy lesson?
Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Unix Timestamps and date()
- The DateTime Class
- Date Arithmetic with DateInterval
- Timezones in PHP