Change date

Hi guys

Is it possible to change a variable from this date format

01-05-2009

to this

2009-05-01

Thanks in advance for your help

$tgt = '01-05-2011';
$part = list($d, $m, $y) = explode( '-', $tgt );
echo $part[2] . '-' . $part[1] . '-'.  $part[0];

As long as $tgt is 1st May 2011 and you want 2011 May 1st, this is probably the most reliable method. You can use strtotime() but really, is 01-02-2011 the first of Feb or 2nd of Jan?

Curio. Why are you creating both a $part array and $m, $d, $y strings at the same time?

$part = list($d, $m, $y) = explode( '-', $tgt );

Either $part = explode( ‘-’, $tgt ); or list( $d, $m, $y ) = explode( ‘-’, $tgt ); alone would give you what you need.


$date = implode('-', array_reverse(explode('-', $date)));

Or… the best option, IMHO:


$date = date('Y-m-d', strtotime($date));

How right you are, thanks for correcting me - what a silly error!

Taking the OPs example at face value, nobody can say whether it is 1st May or 5th Jan with any certainty except the OP - hence my (botched) use of explode().