How to Convert One Date Format into Another in PHP?

Last updated on August 23, 2023 by Ayaz Ali Shah

We can use PHP built-in function strtotime() and format() method from the DateTime class to convert the date format into another. It is supported by PHP versions 5.2.0, PHP 7, and 8. In this article, we will convert the date format using both approaches. Let’s start with the format() method.

Convert Date Through format() Method:

In PHP, we have a DateTime class that has the format() method to convert the date format. Look at below example.

$date = "2023-08-23";
$format = "Y-m-d";

$datetime = DateTime::createFromFormat($format, $date);

$newFormat = "d-M-Y";
$newDate = $datetime->format($newFormat);

echo "Date with old format: $date\n";
echo "Date with new format: $newDate\n";

Below is the output,

Date with old format: 2023-08-23
Date with new format: 23-Aug-2023

In this example, we have $date and $format variable that stores the date and its format. In the next line, we have created a date-time object through the createFromFormat() method that takes two required parameters which first is the format and the second is the date.

After creating the date-time object, we created a $newFormat variable that stores the new or desired format in which the date has to convert. Then finally, we used the format() method from the DateTime class and passed the $newFormat variable in the format() method as an argument. On PHP official documentation we can find all the formatting codes.

Share on:

Related Posts

Tags: Date, PHP,