How to convert mysql date to string in php?

In this tutorial, we will explain to you how you can convert mysql date to string in PHP.

1. Code:

   <?php 	
	function convertMySqlDateToString($mysqlDate, $format = "d-m-Y"){
		if (is_null($mysqlDate) || trim($mysqlDate) == '' || "0000-00-00 00:00:00" == trim($mysqlDate)) {
			return null;
		}
		try {
    		$d = DateTime::createFromFormat('Y-m-d H:i:s', $mysqlDate);
    		if (false === $d) {
    			throw new \Exception ("Invalid date");
    		}
		}catch (\Exception $e) {
		    return $mysqlDate;
		}
		$str = $d->format($format);
		return (false != $str) ? $str : null;
	}
	
	$str = convertMySqlDateToString("2018-11-15 00:00:00", "d-m-Y");
	echo($str);
    ?> 

2. Example:

Input:

convertMySqlDateToString("2018-11-15 00:00:00", "d-m-Y");
convertMySqlDateToString("2018-11-15 00:00:00", "Y-m-d")

Output:

15-11-2018 
2018-11-15