I have a string value in mmddyyyy format that I want to add in the /
to in php. What is the proper way to do this?
I tried
$sDate = "04012023";
$sDate = date_create_from_format('mmddYYYY', $formattedSDate);
print_r($sDate);
but that does not format it as a date!
>Solution :
Assuming your date strings would always be fixed width in the format mmddYYYY
you could use a regex replacement here:
$sDate = "04012023";
$output = preg_replace("/^(\d{2})(\d{2})(\d{4})$/", "$1/$2/$3", $sDate);
echo $output; // 04/01/2023
For another more robust and general approach, we can do a rountrip conversion from string to date, then date back to string in the format desired:
$sDate = "04012023";
$ymd = DateTime::createFromFormat('dmY', $sDate)->format('d/m/Y');
echo $ymd; // 04/01/2023