The Basics
To convert a string to date, we will use two functions: strtotime() and the date() functions. We can also use the DateTime::createFromFormat method.
We will start with the combination of strtotime() and date() functions.
PHP strtotime() Function
The PHP strtotime() method allows you to convert a human-readable time format to Unix time.
Unix time refers to the number of seconds elapsed since 1/1/1970 00:00:00.
The function takes a syntax as shown below:
The function takes the timestamp as the argument and returns the date as an integer if the conversion is successful. The function also returns a Boolean false on fail.
NOTE: The function will interpret various formats differently. For example, if you use the separator as a slash, the method will assume the American date and time format as M/D/Y. However, if the separator is a (-), the European format is used (D-M-Y).
To stay on the safe side, use the ISO 8601 (YYYY-MM-DD) format.
Learn more about PHP Date and Time formats in the resource provided below:
https://www.php.net/manual/en/datetime.formats.php
Take a look at the following examples that show how to use the strtotime() function.
The above examples convert various strings to their relevant Unix timestamps.
PHP Date() Function
The following function we will look at is the Date() function. This function takes a Unix timestamp and converts it to a local date and time format. The syntax of the function can be expressed as:
It accepts a date and time format and a timestamp. Once formatted, the function returns the date and time formatted accordingly.
For example, let us convert a specific timestamp to a date and time.
In the example above, we use the date format to convert a specific Unix timestamp to date/Month/Year Hours:minutes seconds format.
Run the code above, and you should get an output as shown below:
Combining Strtotime() and Date()
To convert a specific string to date and time format, we can combine the strtotime() function and date as we have already seen.
Consider the example shown below:
The example below uses the strtotime() function to convert a specific string to a Unix timestamp.
We then use the date function to convert the timestamp to a specific date and time format.
Method 2 – Use DateTime::createFromFormat()
The other method we can use to create a DateTime from a string is the DateTime::createFromFormat(). This is a built-in PHP function available in PHP 5.2 and higher. It returns a DateTime object representing the date and time in a specified format.
The example below shows how to use it.
$datenew = DateTime::createFromFormat("Y-m-d", "2022-06-06");
echo $datenew->format("Y-m-d"), "\n";
?>
The above code should return the date.
Conclusion
This guide taught you how to convert a specific string to a date and time format using built-in PHP methods.
Thanks for reading!