How to change date format in PHP?
To convert the date-time format we use to PHP functions strtotime() and date().
We change the date format from one format to another. For example – we have stored date in MM-DD-YYYY format in a variable, and we want to change it to DD-MM-YYYY format.
We can achieved this conversion by using strtotime() and date() function. These are the built-in functions of PHP. The strtotime() first converts the date into the seconds, and then date() function is used to reconstruct the date in any format. Below some examples are given to convert the date format.
1. Change YYYY-MM-DD to DD-MM-YYYY
In the below example, we have date 2020-09-15 in YYYY-MM-DD format, and we will convert this to 15-09-2020 in DD-MM-YYYY format.
- <?php
- $orgDate = “2012-09-15”;
- $newDate = date(“d-m-Y”, strtotime($orgDate));
- echo “New date format is: “.$newDate. ” (MM-DD-YYYY)”;
- ?>
Output
New date format is: 15-09-2020 (DD-MM-YYYY)
2. Change YYYY-MM-DD to MM-DD-YYYY
In the below example, we have date 2020-10-27 in YYYY-MM-DD format, and we will convert this to 10-27-2020 (MM-DD-YYYY) format.
- <?php
- $orgDate = “2020-10-27”;
- $newDate = date(“m-d-Y”, strtotime($orgDate));
- echo “New date format is: “.$newDate. ” (MM-DD-YYYY)”;
- ?>
Output
New date format is: 10-27-2020 (MM-DD-YYYY)
3. Change DD-MM-YYYY to YYYY-MM-DD
In the below example, we have date 27-10-2020 in DD-MM-YYYY format, and we will convert this to 2020-10-27 (YYYY-MM-DD) format.
- <?php
- $orgDate = “27-10-2020”;
- $newDate = date(“Y-m-d”, strtotime($orgDate));
- echo “New date format is: “.$newDate. ” (YYYY-MM-DD)”;
- ?>
Output
New date format is: 2020-10-27 (YYYY-MM-DD)
4. Change DD-MM-YYYY to YYYY/MM/DD
DD-MM-YYYY format is converted to the YYYY-MM-DD format, and also dashes (-) will be replaced with slash (/) sign.
- <?php
- $orgDate = “27-10-2020”;
- $date = str_replace(‘-“‘, ‘/’, $orgDate);
- $newDate = date(“Y/m/d”, strtotime($date));
- echo “New date format is: “.$newDate. ” (YYYY/MM/DD)”;
- ?>
Output
date format is: 2020/10/27 (YYYY/MM/DD)
5. Change date time to another format
Here in the below example, we will convert the date format MM-DD-YYYY to YYYY-DD-MM format and 12 hours time clock to 24 hours time clock.
- <?php
- $date = “27/10/2020 5:35 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;
- ?>
Output
New date time format is: 2020/10/27 17:35:00

0 Comments