Converting string to Date and DateTime PHP

This is very common functionality we use while developing any application. There are several functions available with PHP to achieve, 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!!!.

 



Your feedbacks are most welcome..