PHP Function Reference

PHP date_interval_create_from_date_string() Function



The PHP date_interval_create_from_date_string() function uses the normal date parsers and sets up a DateInterval from the relative parts of the parsed string. This function is an alias of DateInterval::createFromDateString() method.

Syntax

//Object-oriented style
public DateInterval::createFromDateString(datetime)

//Procedural style
date_interval_create_from_date_string(datetime)

Parameters

datetime Required. Specify a date with relative parts. Specifically, the relative formats supported by the parser used for strtotime() and DateTime will be used to construct the DateInterval.

Return Value

Returns a new DateInterval instance on success, or false on failure.

Example: using both styles

The example below shows the usage of date_interval_create_from_date_string() function.

<?php
//creating a DateTime object
$date1 = date_create("10-Mar-2015 5:10:25");
$date2 = date_create("10-Mar-2015 5:10:25");

//datetime string
$datetime_str = "2 years 5 months 10 days 5 hours 35 minutes";

//creating a date interval from date string
//string using object-oriented style
$interval1 = DateInterval::createFromDateString($datetime_str);
date_add($date1, $interval1);
echo date_format($date1, 'd-M-Y H:i:s')."\n";

//creating a date interval from date string
//string using Procedural style
$interval2 = date_interval_create_from_date_string($datetime_str);
date_add($date2, $interval2);
echo date_format($date2, 'd-M-Y H:i:s')."\n";
?>

The output of the above code will be:

20-Aug-2017 10:45:25
20-Aug-2017 10:45:25

Example: using different relative formats

Consider one more example where some more relative formats are used.

<?php
$interval11 = date_interval_create_from_date_string("last year");
print_r($interval11);

echo "\n";

$interval12 = date_interval_create_from_date_string("next week");
print_r($interval12);
?>

The output of the above code will be:

DateInterval Object
(
    [y] => -1
    [m] => 0
    [d] => 0
    [h] => 0
    [i] => 0
    [s] => 0
    [f] => 0
    [weekday] => 0
    [weekday_behavior] => 0
    [first_last_day_of] => 0
    [invert] => 0
    [days] => 
    [special_type] => 0
    [special_amount] => 0
    [have_weekday_relative] => 0
    [have_special_relative] => 0
)

DateInterval Object
(
    [y] => 0
    [m] => 0
    [d] => 7
    [h] => 0
    [i] => 0
    [s] => 0
    [f] => 0
    [weekday] => 1
    [weekday_behavior] => 2
    [first_last_day_of] => 0
    [invert] => 0
    [days] => 
    [special_type] => 0
    [special_amount] => 0
    [have_weekday_relative] => 1
    [have_special_relative] => 0
)

❮ PHP Date and Time Reference