php

How to Convert a Date Format in PHP?

Working with date formats is a common task in web development, especially when building applications that require the display of date and time information. PHP provides numerous built-in functions that enable users to work with dates and times, which also includes the capability to convert date formats.

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:

DateTime::createFromFormat($format, $date_string);

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:

<?php
$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:

strtotime(string $date);

The following example illustrates the strtotime() use:

<?php
$date_str = '2023-04-24';
$timestamp = strtotime($date_str);
$formatted_date = date('F d, Y', $timestamp);
echo "Original Date: " . $date_str . "\n";
echo "Formatted Date: " . $formatted_date . "\n";
?>

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.

About the author

Awais Khan

I'm an Engineer and an academic researcher by profession. My interest for Raspberry Pi, embedded systems and blogging has brought me here to share my knowledge with others.