Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Regular Expression to Change Date Format

I almost tried for 10 hours to change the date format suits my needs but couldn't success. I have tried Preg_Replace Strotime functions with following examples.

The current date format is : 02-25-2006 Want to convert to: 2006-02-25

Here are the list of examples I have tried:

publishdate = "02-20-2012";  
echo preg_replace("/\d{2}-\d{2}-\d{4}/","$3/$1/$2",$publishdate); 

$dateString= '2006-09-14';
echo date("m/d/Y", strtotime($dateString));



$dateString1= '02-20-2012';
echo date("Y/m/d", strtotime($dateString1));



$date1 = '05-25-2010';
echo date('Y-m-d', strtotime($date1));

$dateString2= '02-20-2012';
echo preg_replace("/(\d{2})-(\d{4})-(\d{2})/","$2/$3/$1",$dateString2);  
like image 920
Maihan Nijat Avatar asked Jun 29 '26 02:06

Maihan Nijat


1 Answers

The easiest way is to use date_create_from_format:

$date1='02-25-2006';
echo($date1);
echo "<br>";
$newdate = date_format(date_create_from_format('m-d-Y', $date1),'Y-m-d'); 
echo $newdate;

Then the output will be 2006-02-25.

like image 75
InNoor Avatar answered Jun 30 '26 20:06

InNoor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!