How to Convert a Date Format in PHP

Here is a short tutorial that represents how to convert a date format in PHP. As a rule, the built-in functions such as strtotime() and date() are used to achieve the desired conversion.

Check out several possible conversion cases below.

Convert YYYY-MM-DD to DD-MM-YYYY

Imagine, that you have kept date 2020-05-15 in MM-DD-YYYY format and intend to change it to 15-05-2020 in the DD-MM-YYYY format.

Here is an example:

<?php

$orgDate = "2020-05-15";
$newDate = date("d-m-Y", strtotime($orgDate));
echo "New date format is: " . $newDate . " (MM-DD-YYYY)";

?>

Convert YYYY-MM-DD to MM-DD-YYYY

Now, imagine having a date 2020-05-15 in YYYY-MM-DD format. Let’s convert it to 05-15-2020 (MM-DD-YYYY) like this:

<?php

 $orgDate = "2020-05-15";
 $newDate = date("m-d-Y", strtotime($orgDate));
 echo "New date format is: " . $newDate . " (MM-DD-YYYY)";

?>

Convert DD-MM-YYYY to YYYY-MM-DD

In this section, consider having a date 15-05-2020 in DD-MM-YYYY format. Below, you can see how to convert it to 2020-05-15 (YYYY-MM-DD) format:

<?php

$orgDate = "15-05-2020";
$newDate = date("Y-m-d", strtotime($orgDate));
echo "New date format is: " . $newDate . " (YYYY-MM-DD)";

?>

Convert DD-MM-YYYY to YYYY/MM/DD

Now, suppose having a date 15-05-2020 in DD-MM-YYYY format. It is separated by dash (-) sign. Let’s try converting it to 2020/05/15 (YYYY/MM/DD) format, separated by slash(/).

Here is how to do that:

<?php

 $orgDate = "15-05-2020";
 $date = str_replace('-"', '/', $orgDate);
 $newDate = date("Y/m/d", strtotime($date));
 echo "New date format is: " . $newDate . " (YYYY/MM/DD)";

?>

Convert Date Time to A Different Format

In this section, you will figure out how to transform date format MM-DD-YYYY to YYYY-DD-MM, as well as12 hours time clock to 24 hours.

Here is an example:

<?php

 $date = "05/15/2020 5:36 PM";

 //converts date and time to seconds
 $sec = strtotime($date);

 //converts seconds into a specific format
 $newdate = date("Y/d/m H:i", $sec);

 //Appends seconds with the time
 $newdate = $newdate . ":00";

 // display converted date and time
 echo "New date time format is: " . $newDate;

?>

In this snippet, we covered several handy solutions. If you want to get more information and answers to Date/Time issues in PHP, we recommend you also to check out this page.