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:

Download  Run Code

 
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'.

Download  Run Code

 
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.

Download  Run Code

 
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.

Download  Run Code

That’s all there is to converting a string to a DateTime in PHP.