The format Method of the DateInterval Class
The format
method of the DateInterval
class converts a time interval into a string representation according to the specified format. It accepts a format string containing special characters as a parameter and returns a formatted string.
Syntax
public DateInterval::format(string $format): string
Special Characters
Specifier | Description | Example |
---|---|---|
%Y |
Number of years (at least 2 |
01, 12 |
%y |
Number of years (without leading zeros) | 1, 12 |
%M |
Number of months (at least 2 |
01, 11 |
%m |
Number of months (without leading zeros) | 1, 11 |
%D |
Number of days (at least 2 |
01, 31 |
%d |
Number of days (without leading zeros) | 1, 31 |
%H |
Number of hours (at least 2 |
01, 23 |
%h |
Number of hours (without leading zeros) | 1, 23 |
%I |
Number of minutes (at least 2 |
01, 59 |
%i |
Number of minutes (without leading zeros) | 1, 59 |
%S |
Number of seconds (at least 2 |
01, 59 |
%s |
Number of seconds (without leading zeros) | 1, 59 |
%R |
Interval sign (+ or -) | +, - |
%r |
Interval sign with explicit indication (- if negative) | , - |
%% |
Percent symbol | % |
Example
Formatting an interval in days and hours:
<?php
$interval = new DateInterval('P2DT5H');
echo $interval->format('%d days, %h hours');
?>
Code execution result:
'2 days, 5 hours'
Example
Formatting an interval in full representation:
<?php
$interval = new DateInterval('P1Y3M5DT7H10M');
echo $interval->format('%y years %m months %d days %h hours %i minutes');
?>
Code execution result:
'1 years 3 months 5 days 7 hours 10 minutes'
Example
Formatting an interval with leading zeros:
<?php
$interval = new DateInterval('PT5H3M');
echo $interval->format('%H:%I');
?>
Code execution result:
'05:03'
See Also
-
the
DateInterval
class,
which represents a time interval -
the
DateTime::format
method,
which formats date and time -
the
date
function,
which formats a timestamp