Convert a String to DateTime in PHP
This article demonstrates how to convert a string to a DateTime in PHP.
The DateTime class is often used for parsing and formatting dates in PHP. The DateTime constructor accepts a string in a supported date and time format and creates a DateTime object initialized from the specified string. Additionally, if you need to parse the DateTime object into another format, you can use the DateTime::format() function.
The following example provides a simple illustration for converting a date string in 'm/d/Y' format to the DateTime instance in 'Y/m/d H:i:s' format:
|
1 2 3 4 5 6 7 8 |
<?php $str = '12/25/2017'; $date = new DateTime($str); $formatted_date = $date->format('Y/m/d H:i:s'); echo $formatted_date; // 2017/12/25 08:00:00 ?> |
However, the DateTime() constructor can only parse a string in valid date and time format. For parsing non-standard date and time formats, you can use the DateTime::createFromFormat() function to parse the specified string to a date in the required format. For example, the following solution parses a string in non-supported format 'd-m-Y H:i:s'.
|
1 2 3 4 5 6 7 8 |
<?php $str = '25-12-2017 8:00:00'; $date = DateTime::createFromFormat('d-m-Y H:i:s', $str); $formatted_date = $date->format('Y/m/d H:i:s'); echo $formatted_date; // 2017/12/25 08:00:00 ?> |
If you prefer procedural functions over object-oriented functions, you can use the date_create_from_format() and date_format() functions, which are aliases of the DateTime::createFromFormat() and DateTime::format() functions, respectively.
|
1 2 3 4 5 6 7 8 |
<?php $str = '25/12/2017 8:00:00'; $date = date_create_from_format('d/m/Y H:i:s', $str); $formatted_date = date_format($date, 'Y/m/d H:i:s'); echo $formatted_date; // 2017/12/25 08:00:00 ?> |
Although DateTime::createFromFormat() is very convenient for parsing a custom date/time string, you might want to check if an error occurs while parsing. This can be done using the return value of createFromFormat(), which returns false on failure.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php $str = '25/12/2017 8:00:00'; $date = DateTime::createFromFormat('d/m/Y H:i:s', $str); if ($date !== false) { $formatted_date = $date->format('Y/m/d H:i:s'); echo $formatted_date; } else { echo "Unable to parse the string: $str"; } /* Output: 2017/12/25 08:00:00 */ ?> |
That’s all there is to converting a string to a DateTime in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)