W3docs

How to Convert a Date Format in PHP

On this page, we are going to help you figure out the main ways of converting date formats in PHP.

Here is a short tutorial that represents how to convert a date format in PHP. As a rule, the built-in functions such as <kbd class="highlighted">strtotime()</kbd> and <kbd class="highlighted">date()</kbd> are used to achieve the desired conversion.

Check out several possible conversion cases below.

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

Imagine that you have a date 2020-05-15 in YYYY-MM-DD format and intend to change it to 15-05-2020 in DD-MM-YYYY format.

Here is an example:

php convert date format with strtotime

<?php

$orgDate = "2020-05-15";
$newDate = date("d-m-Y", strtotime($orgDate));
echo "New date format is: " . $newDate . " (DD-MM-YYYY)";

?>

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

Now, suppose you have a date 2020-05-15 in YYYY-MM-DD format. Let’s convert it to 05-15-2020 (MM-DD-YYYY) like this:

php convert date format

<?php

$orgDate = "2020-05-15";
$newDate = date("m-d-Y", strtotime($orgDate));
echo "New date format is: " . $newDate . " (MM-DD-YYYY)";

?>

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

In this section, suppose you have a date 15-05-2020 in DD-MM-YYYY format. Below, you can see how to convert it to 2020-05-15 (YYYY-MM-DD) format:

php convert date

<?php

$orgDate = "15-05-2020";
$newDate = date("Y-m-d", strtotime($orgDate));
echo "New date format is: " . $newDate . " (YYYY-MM-DD)";

?>

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

Now, suppose you have a date 15-05-2020 in DD-MM-YYYY format, separated by a dash <kbd class="highlighted">(-)</kbd>. Let’s convert it to 2020/05/15 (YYYY/MM/DD) format, separated by a slash(/) .

Here is how to do that:

php change date format

<?php

$orgDate = "15-05-2020";
$date = str_replace('-', '/', $orgDate);
$newDate = date("Y/m/d", strtotime($date));
echo "New date format is: " . $newDate . " (YYYY/MM/DD)";

?>

Convert Date Time to A Different Format

In this section, you will learn how to transform the date format MM-DD-YYYY to YYYY/DD/MM, as well as convert a 12-hour time clock to 24-hour format.

Here is an example:

php change date format

<?php

$date = "05/15/2020 5:36 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 to the time
$newDate = $newDate . ":00";

// display converted date and time
echo "New date time format is: " . $newDate;

?>

In this snippet, we covered several handy solutions. If you want to get more information and answers to Date/Time issues in PHP, we recommend you also to check out this page.