How to convert date string to mysql date in php?
In this tutorial, we will explain to you how you can convert date string to mysql date in PHP.
1. Code:
<?php function convertDateStringToMySqlDate($str, $format, $isDateTime = false){ if (is_null($str) || trim($str) == '') { return null; } $isMysqlDate = isCheckDateWithFormat($str, "Y-m-d H:i:s"); if ($isMysqlDate) { $d = DateTime::createFromFormat("Y-m-d H:i:s", $str); }else{ $d = DateTime::createFromFormat($format, $str); } if (false === $d) { throw new \Exception ("Invalid date"); } if ($isDateTime) { $str = $d->format("Y-m-d H:i:s"); } else { $str = $d->format("d-m-Y"); } return (false != $str) ? $str : null; } function isCheckDateWithFormat($date, $format = 'Y-m-d'){ $d = DateTime::createFromFormat($format, $date); return $d && $d->format($format) === $date; } $str = convertDateStringToMySqlDate("2018-11-15", "Y-m-d", true); echo($str); ?>
2. Example:
Input:
2018-11-15
Output:
2018-11-15 11:39:26