PHP: Convert YYYY-MM-DD to DD-MM-YYYY

OK, so you have a YYYY-MM-DD date format such as 2015-08-10. Now obviously, the YYYY-MM-DD format is more suited for software systems and databases than it is for end-users, which means that it is your task to convert it into a format that is a little more human-friendly.

The first approach is pretty simple. We convert it into a UNIX timestamp using the function strtotime before converting it into 10-08-2015 using the date function:

<?php

//Our YYYY-MM-DD date.
$ymd = '2015-08-10';

//Convert it into a timestamp.
$timestamp = strtotime($ymd);

//Convert it to DD-MM-YYYY
$dmy = date("d-m-Y", $timestamp);

//Echo it
echo $dmy;

As you can see, the process is extremely simple. Once we have converted the string into a UNIX timestamp, we are able to convert it into any kind of date format that we want to.

Some people prefer using PHP’s DateTime object, simply because it’s powerful and it allows you to work with dates using OOP:

<?php

//Our YYYY-MM-DD date.
$ymd = '2015-08-10';

//Create a DateTime object from the YYYY-MM-DD format.
$dateObj= DateTime::createFromFormat('Y-m-d', $ymd);

//Use the d/m/Y format.
$newDateString = $myDateTime->format('d/m/Y');

Lastly, you can completely avoid PHP’s date functions by:

  1. Exploding the string into an array by using the explode function.
  2. Reverse the order of the resulting array by using PHP’s inbuilt array_reverse function.
  3. Convert the array back into a string by using the implode function.
<?php

//The original date format.
$original = '2015-08-10';

//Explode the string into an array.
$exploded = explode("-", $original);

//Reverse the order.
$exploded = array_reverse($exploded);

//Convert it back into a string.
$newFormat = implode("-", $exploded);

//Print it out.
echo $newFormat;

Personally, I think that you’d be crazy to use this approach. Still, it was worth highlighting.