• PHP Video Tutorials

PHP date_interval_format() Function



Definition and Usage

The date_interval_format() function is an alias of DateInterval::format(). This function accepts an interval and a format string as parameters and, formats the given interval in the specified format.

Syntax

date_interval_format($interval, $format)

Parameters

Sr.No Parameter & Description
1

interval (Mandatory)

This is an object of the DateInterval you need to format.

2

format (Mandatory)

This is a string value, specifying the format.

Return Values

This function returns the formatted interval

PHP Version

This function was first introduced in PHP Version 5.3 and, works with all the later versions.

Example

Following example demonstrates the usage of the date_interval_create_from_date_string() function −

<?php
  $interval = new DateInterval('P25DP8MP9Y');
  $format = "%d days;
  $res = date_interval_format($interval, $format);
  print($res);  
?>

This will produce following result −

25 days

Example

Unlike other date/time functions date_interval_format() doesn't recalculate carry over points in date and time strings. Therefore if you pass date/time values beyond their boundaries, they will be formatted as it is −

<?php
   $interval = new DateInterval('P45M');
   $format = "%m months";
   $res1 = date_interval_format($interval, $format);
   print($res1); 
  
   $res2 = date_interval_format(new DateInterval('PT30H'), "%h hours");
   print("\n".$res2);
?>

This will produce following result −

45 months
30 hours

Example

Following example calculates the difference between a given date and the current date and formats the result using the date_interval_format function −

<?php
   $date1 = date_create("25-09-1989");
   $date2 = date_create("1-09-2012");
   $interval = date_diff($date1, $date2);
   $res = date_interval_format($interval, '%Y years %d days');
   print($res);  

?>

Example

<?php
print(date_interval_format(new DateInterval('P12D'), "%d days")."\n");
print(date_interval_format(new DateInterval('P7M'), "%m months")."\n");
print(date_interval_format(new DateInterval('P12Y'), "%y years")."\n");
print(date_interval_format(new DateInterval('PT9H'), "%h hours")."\n");
print(date_interval_format(new DateInterval('PT45S'), "%s seconds")."\n");
?>

This will produce following result −

22 years 7 days
12 days
7 months
12 years
9 hours
45 seconds
php_function_reference.htm
Advertisements