Problem:
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).
Solution:
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-
- Use strtotime() function to convert the date to its Unix timestamp, then,
- Use date() function to create your desired date format from the Unix timestamp.
See the example below-
<?php $timestamp = strtotime("2014-05-26"); echo date("m-d-Y", $timestamp); ?>
[wpdm_file id=115]
Output:
05-26-2014
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.
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.
<?php $dateObj = DateTime::createFromFormat('Y-m-d', '2014-05-26'); echo $new_date_format = $dateObj->format('m-d-Y'); ?>
[wpdm_file id=116]
Output:
05-26-2014
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’) |