Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Format String To Date With Slashes

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading