
Change Date Format in PHP
In PHP, you can change the date format of a given date using the date()
function or the DateTime
class. Both methods allow you to format a date according to your desired pattern.
Using date()
function:
The date()
function allows you to format a Unix timestamp or a date string into a custom date format. It takes two parameters: the format and the timestamp (optional). If the timestamp is not provided, the current timestamp is used.
Here’s an example of changing the date format using the date()
function:
$originalDate = "2023-07-22";
$newDate = date("d/m/Y", strtotime($originalDate));
echo "Original Date: " . $originalDate . "<br>";
echo "Formatted Date: " . $newDate;
Output:
Original Date: 2023-07-22
Formatted Date: 22/07/2023
In this example, the strtotime()
function is used to convert the original date string “2023-07-22” into a Unix timestamp, which is then formatted using the date()
function with the pattern “d/m/Y” (day/month/year).
Using DateTime
class:
The DateTime
class provides an object-oriented way to handle dates in PHP. You can create a DateTime
object and then use the format()
method to change the date format.
Here’s an example of changing the date format using the DateTime
class:
$originalDate = "2023-07-22";
$dateTime = new DateTime($originalDate);
$newDate = $dateTime->format("d/m/Y");
echo "Original Date: " . $originalDate . "<br>";
echo "Formatted Date: " . $newDate;
Output:
Original Date: 2023-07-22
Formatted Date: 22/07/2023
In this example, we create a DateTime
object from the original date string “2023-07-22” and then use the format()
method with the pattern “d/m/Y” to get the formatted date.
Both methods are valid ways to change the date format in PHP. Choose the one that fits your coding style and requirements. The DateTime
class provides more advanced date manipulation capabilities, while the date()
function is simpler and more straightforward for basic date formatting.