How to Convert One Date Format to Another in PHP?


You have a date (for ex. in this format, yyyy-mm-dd) and you want to change the date format to another one(ex. mm-dd-yyyy).


You can convert date format in PHP in few ways. In the following we’ll discuss two ways.

Method 1: Using strtotime() and date() function

You can convert one date format to another by the following two steps-

  1. Use strtotime() function to convert the date to its Unix timestamp, then,
  2. Use date() function to create your desired date format from the Unix timestamp.

See the example below-

$timestamp = strtotime("2014-05-26");
echo date("m-d-Y", $timestamp);

[wpdm_file id=115]


How it works:
strtotime() function takes the date 2014-05-26 as string and converts it to its equivalent timestamp. Then, date() function converts the timestamp to the m-d-Y format.

If you want to convert your date to different format check PHP date function page to find out other formatting characters available.

Please make sure that you followed the supported date and time formats when inserting date time as parameter in strtotime() function.

Method 2: Using createFromFormat() and format() methods of the dateTIme class from SPL

This method is better and smarter solution than the previous one. PHP provides some ready-made classes (called SPL – Standard PHP Library) to solve everyday problems. To solve date related issues, it has DateTime class. We’ll use this class.

$dateObj = DateTime::createFromFormat('Y-m-d', '2014-05-26');
echo $new_date_format = $dateObj->format('m-d-Y');

[wpdm_file id=116]


How it works:

Line 2 First we inform PHP that the supplied date(second parameter – 2014-05-26) is in “Y-m-d” format(first parameter). The method createFromFormat() will convert the date into a new DateTime object($dateObj) based on the format.
Line 3 The format() function formats the DateTIme object($dateObj) to a date according the date format specified in the parameter(‘m-d-Y’)

You can also convert the date format to different one. To know more about the formatting options, see createFromFormate() method.