How to convert date to different format in php?
To convert the date-time format PHP provides strtotime() and date() function. We change the date format from one format to another.
1. Code:
<?php
function convertDateToDifferentFormat($date1, $format1, $format2){
if (is_null($date1) || trim($date1) == '' || "0000-00-00 00:00:00" == trim($date1)) {
return null;
}
$date = DateTime::createFromFormat($format1, $date1);
if (false === $date) {
throw new \Exception ("Invalid date");
}
$str = $date->format($format2);
return (false != $str) ? $str : null;
}
$str = convertDateToDifferentFormat("2022-06-10 06:32:16", "Y-m-d H:i:s", "d-m-Y");
echo($str);
?>
2. Example:
Input:
"2022-06-10 06:32:16", "Y-m-d H:i:s", "d-m-Y";
Output:
10-06-2022