How To Change Date Format In PHP?


Share:
Published By: Admin, Published On: Apr 09, 2021, Category: PHP

Hello Friends,

Now In this blog you'll learn How To Change Date Format In PHP? To convert the date-time format PHP provides strtotime() and date() function. We transmute the date format from one format to another. For example - we have stored date in MM-DD-YYYY format in a variable, and we optate to change it to DD-MM-YYYY format.

We can achieve this conversion by utilizing 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 utilized to reconstruct the date in any format. Below some examples are given to convert the date format.

Convert YYYY-MM-DD to DD-MM-YYYY

Now, Let's see below example, we have date 1997-08-15 in YYYY-MM-DD format, and we will convert this to 15-08-1997 in DD-MM-YYYY format.

Example : YYYY-MM-DD to DD-MM-YYYY
<?php

    $original_date = "1997-08-15";  
    $new_date = date("d-m-Y", strtotime($original_date));  
    echo "New date format is: ".$new_date. " (DD-MM-YYYY)";

?>
Output
New date format is: 15-08-1997 (DD-MM-YYYY)

Convert YYYY-MM-DD to MM-DD-YYYY

Now, Let's see another example of change date formate YYYY-MM-DD to MM-DD-YYYY

Example : YYYY-MM-DD to MM-DD-YYYY
<?php

    $original_date = "1997-08-15";  
    $new_date = date("m-d-Y", strtotime($original_date));  
    echo "New date format is: ".$new_date. " (MM-DD-YYYY)";

?>
Output
New date format is: 08-15-1997 (MM-DD-YYYY) 

Convert DD-MM-YYYY to YYYY-MM-DD

In the below example, we have date 15-08-1997 in DD-MM-YYYY format, and we will convert this to 1997-08-15 (YYYY-MM-DD) format.

Example : DD-MM-YYYY to YYYY-MM-DD
<?php

    $original_date = "1997-08-15";  
    $new_date = date("Y-m-d", strtotime($original_date));  
    echo "New date format is: ".$new_date. " (YYYY-MM-DD)";

?>
Output
New date format is: 1997-08-15 (YYYY-MM-DD) 

Convert DD-MM-YYYY to YYYY/MM/DD

Suppose we have date 15-08-1997 in DD-MM-YYYY format disunited by dash (-) sign. We optate to convert this to 1997/08/15 (YYYY/MM/DD) format, which will be dissevered by the slash (/). In the below example, DD-MM-YYYY format is converted to the YYYY-MM-DD format, and also dashes (-) will be superseded with slash (/) sign.

Example : DD-MM-YYYY to YYYY/MM/DD
<?php

    $original_date = "1997-08-15";  
    $date = str_replace('-"', '/', $original_date);  
    $new_date = date("Y/m/d", strtotime($date));  
    echo "New date format is: ".$new_date. " (YYYY/MM/DD)";

?>
Output
New date format is: 1997/08/15 (YYYY/MM/DD) 

It will help you..

Share: