Converting string to Date and DateTime PHP

Suresh Kamrushi
1 min readNov 25, 2020

This is very common functionality we use while developing any application. There several functions available with PHP to acheive, but I would like to share the best way to do it with is using DateTime

DateTime allow you to get the date and time from the server and format according to your requirements. To reduce efforts i have created a small wrapping function/method which is as below:

public function formatDate($date,$expectedFormat = 'j-M-Y', $currentFormat = 'Y-m-d'){
$date = DateTime::createFromFormat($currentFormat, $date);
return $date->format($expectedFormat);
}

You can call this function and pass any format datetime and get any other format as per your requirement.

Few samples:

echo formatDate("2020-11-20","m/d/Y","Y-m-d");   //output : 11/20/2020
echo formatDate("2020-11-20 20:57","m/d/Y h:i A","Y-m-d H:i"); output: 11/20/2020 08:57 PM
echo formatDate("2020-11-20 20:57","M j, Y","Y-m-d H:i"); output: Nov 20, 2020

Hope this will help someone!!!.

Source : http://sforsuresh.in/converting-string-to-date-and-datetime-PHP

--

--