3

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);  
Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Maihan Nijat
  • 9,054
  • 11
  • 62
  • 110

2 Answers2

2

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.

skuntsel
  • 11,624
  • 11
  • 44
  • 67
InNoor
  • 41
  • 6
1

ad regexp:

you must mark capture groups in your regexp if you want to use partial matches in your substituting expression! you do so by enclosing parts of your regexp pattern in parentheses. so your regexp should be /(\d{2})-(\d{2})-(\d{4})/. more info in the regexp docs, notably the section on subpatterns.

ad strtotime:

if you choose - as a date part separator, days must come first. thus 02/20/2012 will work as well as 20-02-2012 while 02-20-2012 won't. for more details on supported date/time formats consult the docs.

collapsar
  • 17,010
  • 4
  • 35
  • 61