0PricingLogin
PHP Academy · Lesson

Date Arithmetic with DateInterval

Add and subtract time periods using DateInterval and modify().

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;    // 10

All lessons in this course

  1. Unix Timestamps and date()
  2. The DateTime Class
  3. Date Arithmetic with DateInterval
  4. Timezones in PHP
← Back to PHP Academy