Clue Mediator

How to convert a date format in PHP

📅January 11, 2021
🗁PHP

Today, we’ll discuss how to convert a date format in PHP. For example if we have date in YYYY-MM-DD format and need to convert it to DD-MM-YYYY format.

Using built-in PHP functions strtotime() and date(), we can easily convert date format.

  • strtotime() function - To convert any textual datetime to a Unix timestamp.
  • date() function - To convert timestamp into desired date format.

You can also check Add or Subtract days, month and year to a date using PHP.

Let’s start with an example.

Convert a date format

  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

1. Convert YYYY-MM-DD to DD-MM-YYYY

In the following example, we will change the date from yyyy-mm-dd format to dd-mm-yyyy.

<!--?php
$originalDate = "2021-01-07";
$newDate = date("d-m-Y", strtotime($originalDate));
print_r($newDate);
?-->

// Output: 07-01-2021

2. Convert YYYY-MM-DD to MM-DD-YYYY

In this second example, we will change the date from yyyy-mm-dd format to mm-dd-yyyy.

<!--?php
$originalDate = "2021-01-07";
$newDate = date("m-d-Y", strtotime($originalDate));
print_r($newDate);
?-->

// Output: 01-07-2021

3. Convert DD/MM/YYYY to YYYY-MM-DD

In the last example, we will change the date from dd/mm/yyyy format to yyyy-mm-dd.

<!--?php
$originalDate = "07/01/2021";
$originalDate = str_replace('/', '-', $originalDate );
$newDate = date("Y-m-d", strtotime($originalDate));
print_r($newDate);
?-->

// Output: 2021-01-07

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂