Swap days and months in PHP – quick and dirty MM/DD/YY to DD/MM/YY

Problem

I have a ton of date strings in the stupid US style dd/mm/yy format. i.e. 12/24/09 being 24th September 2009. I need to convert them to the UK style dd/mm/yy.

Solution 1

As a string in PHP is really just an array of characters, the simplest fix was to address the individual number characters by their positions within the sting, and rearrange them into the format I wanted:

$d = "12/24/09";
$d = $d[3].$d[4]."/".$d[0].$d[1]."/".$d[6].$d[7];
echo $d; // displays "24/12/19".

Solution 2

I posted my solution on twitter (@hutchings) and asked for comments and @londonhackspace organiser Jonty came back with the following elegant (and much cleverer) suggestion:

$d = "12/24/09";
$d = preg_replace('|(d+)/(d+)/(d+)|', '$2/$1/$3', $d);
echo $d; // displays "24/12/19".

So provided you know that your original string is in US format, both these solutions can be used. In my testing I found solution 1 executed more quickly, but isn’t as pleasing to look at 🙂 Cheers Jonty.

Leave a Reply

Your email address will not be published. Required fields are marked *