PHP Function Reference

PHP DateInterval - format() Method



The PHP DateInterval::format() method formats the interval. The date_interval_format() function is an alias of this method.

Syntax

//Object-oriented style
public DateInterval::format(format)

//Procedural style
date_interval_format(object, format)

Parameters

object Required. For procedural style only: A DateInterval object.
format Required. Specify the format. The characters mentioned in the table below can be used in the format parameter string. Each format character must be prefixed by a percent sign (%).

format parameter string

Format characterDescriptionExample values
%Literal %%
YYears, numeric, at least 2 digits with leading 001, 03
yYears, numeric1, 3
MMonths, numeric, at least 2 digits with leading 001, 03, 12
mMonths, numeric1, 3, 12
DDays, numeric, at least 2 digits with leading 001, 03, 31
dDays, numeric1, 3, 31
aTotal number of days as a result of a DateTime::diff() or (unknown) otherwise4, 18, 8123
HHours, numeric, at least 2 digits with leading 001, 03, 23
hHours, numeric1, 3, 23
IMinutes, numeric, at least 2 digits with leading 001, 03, 59
iMinutes, numeric1, 3, 59
SSeconds, numeric, at least 2 digits with leading 001, 03, 57
sSeconds, numeric1, 3, 57
FMicroseconds, numeric, at least 6 digits with leading 0007701, 052738, 428291
fMicroseconds, numeric7701, 52738, 428291
RSign "-" when negative, "+" when positive-, +
rSign "-" when negative, empty when positive-,

Return Value

Returns the formatted interval.

Example: using both styles

The example below shows the usage of DateInterval::format() method.

<?php
//creating DateTime objects
$date1 = new DateTime("10-Mar-2015");
$date2 = new DateTime("25-Jun-2016");

//creating a interval DateInterval object
//by taking difference of two dates
$diff = $date1->diff($date2);

//formatting interval using object-oriented style
echo $diff->format("%a total days\n");
echo $diff->format("%m months, %d days \n");
echo $diff->format("%y years, %m months, %d days \n");

//formatting interval using Procedural style
echo date_interval_format($diff, "%a total days \n");
echo date_interval_format($diff, "%m month, %d days \n");
echo date_interval_format($diff, "%y years, %m months, %d days \n");
?>

The output of the above code will be:

473 total days
3 months, 15 days 
1 years, 3 months, 15 days 
473 total days 
3 month, 15 days 
1 years, 3 months, 15 days 

Example: sign with DateInterval

Consider the example below where interval strings are produced with proper sign.

<?php
//creating DateTime objects
$date1 = new DateTime("10-Mar-2015");
$date2 = new DateTime("25-Jun-2016");

//creating a interval DateInterval object
//by taking difference of two dates
$diff = $date2->diff($date1);

echo date_interval_format($diff, "%a total days \n");
echo date_interval_format($diff, "%R%a total days \n");
?>

The output of the above code will be:

473 total days 
-473 total days 

❮ PHP Date and Time Reference