How to Change Date Format in PHP

Working with date formats is a common task in web development. PHP provides several functions and classes to manipulate and format dates to meet your specific requirements.

There are two easy ways that you can use to change the date format in PHP, using the date() function and the DateTime class.

1. Using the date() Function:

The date() function is the most straightforward way to change the format of a date in PHP. It allows you to format a date according to your needs by specifying a format string.

Here’s a basic example of how to change the date format using date():

<?php
$originalDate = "2023-10-02"; // Date in "Y-m-d" format
$newDateFormat = date("d/m/Y", strtotime($originalDate)); // Desired format: "d/m/Y"
echo "Original Date: $originalDate <br>";
echo "New Date Format: $newDateFormat";

Output:

Original Date: 2023-10-02
New Date Format: 02/10/2023

In this example, we use strtotime() to convert the original date into a Unix timestamp, which is necessary for the date() function.

Here are some common format characters you can use with the date() function:

Y: Four-digit year (e.g., 2023) m: Month with leading zeros (01 to 12) d: Day of the month with leading zeros (01 to 31) H: Hour in 24-hour format with leading zeros (00 to 23) i: Minutes with leading zeros (00 to 59) s: Seconds with leading zeros (00 to 59) You can customize the format string to achieve the desired date format.


2. Using the DateTime Class:

The “DateTime” class provides a more powerful and flexible way to manipulate and format dates in an object-oriented manner.

Here’s how to change the date format using the DateTime class:

<?php
$originalDate = "2023-10-02";
$dateTime = new DateTime($originalDate);
$newDateFormat = $dateTime->format("d F, Y");
echo "Original Date: $originalDate<br>";
echo "New Date Format: $newDateFormat";

Output:

Original Date: 2023-10-02
New Date Format: 02 October, 2023

In this example, we create a DateTime object from the original date, and then we use the format() method to change the date format.