PHP Function Reference

PHP DateInterval - createFromDateString() Method



The PHP DateInterval::createFromDateString() method uses the normal date parsers and sets up a DateInterval from the relative parts of the parsed string. The date_interval_create_from_date_string() function is an alias of this 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 DateInterval::createFromDateString() method.

<?php
//creating a DateTime object
$date1 = new DateTime("10-Mar-2015 5:10:25");
$date2 = new DateTime("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);
$date1->add($interval1);
echo $date1->format('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);
$date2->add($interval2);
echo $date2->format('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 = DateInterval::createFromDateString("last year");
print_r($interval11);

echo "\n";

$interval12 = DateInterval::createFromDateString("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