Tags
Asked 2 years ago
9 Jun 2021
Views 220
steave

steave posted

how to Converte string to Date and DateTime in php ?

how to Converte string to Date and DateTime in php ?
jqueryLearner

jqueryLearner
answered Apr 26 '23 00:00

To convert a string to date or datetime in PHP, you can use the strtotime () and date() functions.

Here's an example of how to convert a string to date:



$string = '2022-05-12';
$date = date('Y-m-d', strtotime($string));
echo $date; // output: 2022-05-12

And here's an example of how to convert a string to datetime :



$string = '2022-05-12 14:30:00';
$datetime = date('Y-m-d H:i:s', strtotime($string));
echo $datetime; // output: 2022-05-12 14:30:00

Note that strtotime () parses the string and returns a Unix timestamp (number of seconds since January 1 1970 00:00:00 UTC), which is then formatted using date(). Also, strtotime () works with many different date and time formats, but it's not perfect and may not work with all formats. In such cases, you can use the DateTime class to parse the string.
Post Answer