248 of 410 menu

The createFromDateString Method of the DateInterval Class

The static method createFromDateString of the DateInterval class converts a string description of a time interval into a DateInterval object. It accepts as a parameter a string with a date format that the strtotime function understands. Returns a DateInterval object or false on error.

Syntax

DateInterval::createFromDateString(string $datetime): DateInterval|false

Example

Let's create an interval of 2 days:

<?php $interval = DateInterval::createFromDateString('2 days'); print_r($interval); ?>

Code execution result:

DateInterval Object ( [d] => 2 [h] => 0 [i] => 0 [s] => 0 ... )

Example

Let's create an interval of 1 month and 5 days:

<?php $interval = DateInterval::createFromDateString('1 month + 5 days'); print_r($interval); ?>

Code execution result:

DateInterval Object ( [m] => 1 [d] => 5 [h] => 0 [i] => 0 [s] => 0 ... )

Example

Let's create an interval of 3 hours and 30 minutes:

<?php $interval = DateInterval::createFromDateString('3 hours + 30 minutes'); print_r($interval); ?>

Code execution result:

DateInterval Object ( [h] => 3 [i] => 30 [s] => 0 ... )

See Also

  • the DateInterval class,
    which represents a time interval
  • the strtotime function,
    which converts a textual date description into a timestamp
  • the DateTime class,
    which works with date and time
byenru