220 of 410 menu

The date_interval_create_from_date_string Function

The date_interval_create_from_date_string function converts a textual description of an interval into a date object. This object can be used with the date_add and date_sub functions. The interval string uses natural language to specify the period.

Syntax

date_interval_create_from_date_string(string $time);

Example

Create an interval of 2 days and 6 hours:

<?php $interval = date_interval_create_from_date_string('2 days + 6 hours'); print_r($interval); ?>

Code execution result:

DateInterval Object ( [d] => 2 [h] => 6 )

Example

Create a complex interval (1 month, 2 weeks, and 3 days):

<?php $interval = date_interval_create_from_date_string('1 month + 2 weeks + 3 days'); print_r($interval); ?>

Code execution result:

DateInterval Object ( [m] => 1 [d] => 17 )

Supported Formats

The function understands the following units of measurement:

  • year/years
  • month/months
  • day/days
  • week/weeks
  • hour/hours
  • minute/minutes
  • second/seconds

See Also

  • the date_add function,
    which adds an interval to a date
  • the date_sub function,
    which subtracts an interval from a date
  • the date_create function,
    which creates a DateTime object
byenru