PHP Function Reference

PHP date_interval_format() Function



The PHP date_interval_format() function formats the interval. This function is an alias of DateInterval::format() 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 date_interval_format() function.

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

//creating a interval DateInterval object
//by taking difference of two dates
$diff = date_diff($date1,$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 = date_create("10-Mar-2015");
$date2 = date_create("25-Jun-2016");

//creating a interval DateInterval object
//by taking difference of two dates
$diff = date_diff($date2,$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