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);  

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I like this solution: clean and takes automatically care of missing/to-be-added zeroes.
This solution dont work if your string is a phrase or a json stringified
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.