Oihana PHP Standards

toIso8601Duration.php

Table of Contents

Functions

toIso8601Duration()  : string
Converts a DateInterval object to its ISO 8601 duration string representation.

Functions

toIso8601Duration()

Converts a DateInterval object to its ISO 8601 duration string representation.

toIso8601Duration(DateInterval $interval) : string

This function generates a normalized ISO 8601 duration string from a PHP DateInterval object. The ISO 8601 duration format follows the pattern: P[n]Y[n]M[n]DT[n]H[n]M[n]S where P is the duration designator, T separates date and time components.

Components:

  • Y: years
  • M: months (before T) or minutes (after T)
  • D: days
  • H: hours
  • M: minutes
  • S: seconds

Only non-zero components are included in the output string. If all components are zero, returns "P0D" (zero duration).

Parameters
$interval : DateInterval

The DateInterval object to convert

Tags
example
// Create a duration of 1 year, 2 months, and 3 days
$interval = new DateInterval('P1Y2M3D');
echo toIso8601Duration($interval); // Output: "P1Y2M3D"
// Create a duration of 4 hours and 30 minutes
$interval = new DateInterval('PT4H30M');
echo toIso8601Duration($interval); // Output: "PT4H30M"
// Create a complex duration
$interval = new DateInterval('P2Y3M15DT12H45M30S');
echo toIso8601Duration($interval); // Output: "P2Y3M15DT12H45M30S"
// Create an interval from date difference
$start = new DateTime('2024-01-01');
$end = new DateTime('2024-12-31');
$interval = $start->diff($end);
echo toIso8601Duration($interval); // Output: "P11M30D"
// Zero duration
$interval = new DateInterval('PT0S');
echo toIso8601Duration($interval); // Output: "P0D"
link

ISO 8601 Duration specification

PHP DateInterval documentation

author

Marc Alcaraz (ekameleon)

since
1.0.1
Return values
string —

The ISO 8601 duration string (e.g., "P1Y2M3DT4H5M6S", "PT30M", "P0D")

On this page

Search results