CodeBlanks Logo Icon CodeBlanks

DateInterval and DatePeriod

PHP course · Intermediate · Lesson 109/115

Learn date differences with DateInterval and walking date ranges with DatePeriod.

Durations with DateInterval

The DateInterval class represents a duration: one day, one month, one hour and so on. The duration is given as an ISO 8601 string: 'P1D' is one day, 'P1M' one month, 'P1Y' one year, 'PT1H' one hour.

You add one day to a DateTime object with ->add(new DateInterval('P1D')). Use ->sub() to subtract.

P starts the period, T starts the time part; dates come after P, times after T.

Date ranges with DatePeriod

The DatePeriod class walks a date range at a fixed interval. It takes a start DateTime, a DateInterval and an end DateTime.

For example, to list every day from 1 January to 7 January, build new DatePeriod($start, new DateInterval('P1D'), $end) and loop with foreach. Each iteration yields a DateTime object.

This is very handy for range-based work like calendars or reports.

Exercise Add one day to a DateTime

Create an object with new DateTime('2024-01-01') and assign it to $date. Then add one day with $date->add(new DateInterval('P1D')) and print it with echo $date->format('Y-m-d').

Show example solution
Create with $date = new DateTime('2024-01-01'); add $date->add(new DateInterval('P1D')); then write echo $date->format('Y-m-d');
Example solution:
<?php
date_default_timezone_set('UTC');

$date = new DateTime('2024-01-01');
$date->add(new DateInterval('P1D'));
echo $date->format('Y-m-d');

Test yourself

  1. What does new DateInterval('P1D') represent?

    • A 1-hour duration
    • A 1-day duration
    • A 1-month duration
    • A 1-year duration
    Show answer

    A 1-day duration — Correct. 'P1D' represents a one-day duration.

  2. Create a one-day interval

    $interval = new DateInterval('____');
    Show answer
    $interval = new DateInterval('P1D');
  3. Match duration specs

    'P1D'
    1 day
    'P1M'
    1 month
    'P1Y'
    1 year
    'PT1H'
    1 hour

All lessons in Intermediate