In this article, we will explore different techniques for converting a date format in PHP, along with examples and explanations.
Convert a Date Format in PHP
There are commonly two methods to convert a date format in PHP, which are as follows:
1: Using DateTime::createFromFormat() Method
The DateTime class in PHP provides a powerful set of tools to work with dates and times. One of the most useful methods provided by this class is createFromFormat(), which allows you to create a DateTime object from a string representation of a date, using a specified format.
The syntax for using DateTime::createFromFormat() function is as follows:
Here, $format is the format of the input date string, and $date_string is the date string that you want to convert.
For example, let’s say you have a date string in the format “2023-04-24” and you want to convert it to the format “April 24, 2023“. Use the below-given code:
$date_str = '2023-04-24';
$date = DateTime::createFromFormat('Y-m-d', $date_str);
$formatted_date = $date->format('F d, Y');
echo "Original Date: " . $date_str . "\n";
echo "Formatted Date: " . $formatted_date . "\n";
?>
Output
2: Using strtotime() Function
In PHP, the strtotime() function is another useful way for converting a date from one format to another and it works by converting a string with a date and time format into a Unix timestamp, enabling the date to be formatted in any desired way using the date() function.
The syntax to use strtotime() function is given below:
The following example illustrates the strtotime() use:
Output
Conclusion
PHP provides various methods for converting date formats, such as DateTime::createFromFormat() and strtotime() functions. These methods are handy tools that allow developers to work with dates and times flexibly and efficiently.