date_interval_create_from_date_string()
The date_interval_create_from_date_string() function is a built-in PHP function that creates a new DateInterval object based on a string representation of the
What is date_interval_create_from_date_string()?
The date_interval_create_from_date_string() function is a built-in PHP function that creates a new DateInterval object based on a string representation of the interval. It accepts a single string parameter.
Note: This function was deprecated in PHP 8.2 and is scheduled for removal in a future version.
How does it work?
The function parses the provided string using strtotime(). Common formats include relative time strings like '+1 day', '1 week', or '2 hours 30 minutes'.
It returns a DateInterval object on success, or false if the string cannot be parsed.
Error handling: Always check the return value before using the object. For modern PHP, using the DateInterval constructor directly is recommended as a reliable fallback.
Here's an example of how to use the function:
Basic usage
<?php
$interval = date_interval_create_from_date_string('1 day');In this example, we're creating a new DateInterval object that represents a one-day interval.
Examples
Let's take a look at some examples of how to use the function.
Example 1: Adding an interval to a date
This example creates a one-day interval and adds it to a DateTime object:
Adding an interval to a date in PHP
<?php
$date = new DateTime('2023-03-03');
$interval = date_interval_create_from_date_string('1 day');
$date->add($interval);
echo $date->format('Y-m-d');The output of this code will be:
2023-03-04Example 2: Formatting an interval
This example creates a one-month interval and formats it using DateInterval::format():
Formatting an interval of a date in PHP
<?php
$interval = date_interval_create_from_date_string('1 month');
echo $interval->format('%m months');The output of this code will be:
01 monthsTips for optimizing performance
Here are some tips for optimizing the performance of the function:
- Use concise relative strings (e.g.,
'1 day'instead of'P0Y0M1D') to reduce parsing overhead. - Cache
DateIntervalobjects when reused within the same script execution to minimize object instantiation. - Avoid instantiating intervals inside tight loops; pre-define them outside the loop and reuse them as needed.
Conclusion
In this article, we've discussed the date_interval_create_from_date_string() function. Note that it was deprecated in PHP 8.2 and is scheduled for removal in a future version. For modern PHP versions, use the DateInterval constructor directly (e.g., new DateInterval('P1D')). We've explained how the function works, provided examples, and offered tips for optimizing its performance. We hope that this article has been helpful.
Practice
What does the PHP function date_interval_create_from_date_string do?