PHP: Convert Date from one format to another
Some times you need to convert date format, you can use below examples
Example 1
$PDATEX = '2020-06-21'; $date=date_create($PDATEX); echo $DM = date_format($date,"d-m-Y"); echo $DM = date_format($date,"d/m/Y");
Example 2
$myDateTime = DateTime::createFromFormat('Y-m-d', $PDATEX); echo $newDateString = $myDateTime->format('m/d/Y');
Example 3
Data time conversion from date time format
$PDATEX = '29/11/2018, 16:08'; $FArray = (explode(",",$PDATEX)); $SRCDATE = $FArray[0]; $SRCTIME = $FArray[1]; $SRCDATE2 = str_replace('/', '-', $SRCDATE); $FArray2 = (explode("/",$SRCDATE)); $Year = $FArray2[2]; $Month = $FArray2[1]; $Day = $FArray2[0]; $Day = substr($Day,0,2); echo $NewDate = $Year.'-'.$Month.'-'.$Day.' '.$SRCTIME;
Definition and Usage
Some times you encounter data from other Databases and need to handle dates specified in their format, so this example gives you a start point
Code takes date as '29/11/2019, 16:08' you need to convert it to save in MySQL format '2019-11-29 16:08:00'.
$FArray = (explode(",",$PDATEX)); It breakes date in to parts, date part & time part
$SRCDATE = $FArray[0]; Saves date part in $SRCDATE variable
$SRCTIME = $FArray[1]; Saves time part in $SRCTIME variable
$SRCDATE2 = str_replace('/', '-', $SRCDATE); str_replace is PHP function which finds / and replces - as in MySQL date
Above example is enough and you will get date part, but you can also do so in another way
$FArray2 = (explode("/",$SRCDATE)); It further breakes $SRCDATE into day, month and year parts which you can assign to different variables to re-assemble in a variable