How to Convert a Date Format in PHP

  1. Convert YYYY-MM-DD to DD-MM-YYYY
  2. Convert YYYY-MM-DD to MM-DD-YYYY
  3. Convert DD-MM-YYYY to YYYY-MM-DD
  4. Convert DD-MM-YYYY to YYYY/MM/DD
  5. Convert Date Time to A Different Format

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:

1 <?php  
2    $orgDate = "2020-05-15";  
3    $newDate = date("d-m-Y", strtotime($orgDate));  
4    echo "New date format is: ".$newDate. " (MM-DD-YYYY)";  
5 ?>

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:

1 <?php  
2    $orgDate = "2020-05-15";  
3    $newDate = date("m-d-Y", strtotime($orgDate));  
4    echo "New date format is: ".$newDate. " (MM-DD-YYYY)";  
5 ?>

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:

1<?php  
2    $orgDate = "15-05-2020";  
3    $newDate = date("Y-m-d", strtotime($orgDate));  
4    echo "New date format is: ".$newDate. " (YYYY-MM-DD)";  
5 ?>

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:

1 <?php  
2    $orgDate = "15-05-2020";  
3    $date = str_replace('-"', '/', $orgDate);  
4    $newDate = date("Y/m/d", strtotime($date));  
5    echo "New date format is: ".$newDate. " (YYYY/MM/DD)";  
6 ?>

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:

1 <?php  
2    $date = "05/15/2020 5:36 PM";  
3
4    //converts date and time to seconds  
5    $sec = strtotime($date);  
6
7    //converts seconds into a specific format  
8    $newdate = date ("Y/d/m H:i", $sec);  
9
10   //Appends seconds with the time  
11   $newdate = $newdate . ":00";  
12
13   // display converted date and time 
14   echo "New date time format is: ".$newDate;  
15 ?>

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.


Do you find this helpful?

Related articles