Hi guys, I'm Jack Pham. In this article, I'm going to share with you a PHP function which can help you quickly reformat your date value.
Background
date
is a type of value in PHP which can be displayed in many formats. To format a date value stored in a variable, we can use the built-in date_format()
function. However, the function only works if your first parameter is a DateTime object
. It doesn't work if you use a date string.
Of course, you can use date_create()
or date_create_from_format()
to convert your date string
to a DateTime object
. However, it may take you a lot of time if you do this usually.
In that case, you use my custom date_reformat()
function to quicken your coding progress
Setup
This function is easy to set up when it doesn't need any external libraries or plugins. Below are the codes and usage:
function date_reformat($date_string, $current_format = 'Y-m-d', $new_format = 'm/d/Y'){
if ($date_string != null && $date_string != '' && date_create_from_format($current_format, $date_string) != false) {
$date_string = date_format(date_create_from_format($current_format, $date_string), $new_format);
}
return $date_string;
}
Usage
Just simply put the function to your code or your helper file, then use it normally:
$date = '2023-02-08';
$date = date_reformat($date);
echo $date; // 02/08/2023
$date = '02/08/2023';
$date = date_reformat($date, 'm/d/Y', 'M d Y');
echo $date; //Feb 08 2023
$date = 'Feb 08 2023';
$date = date_reformat($date, 'M d Y');
echo $date; //02/08/2023
Parameters
There are 3 parameters in the function:
$date_string
(required): Your date string needed to be reformat;$current_format
(optional): The current format of your date string. Default: Y-m-d.$new_format
(optional): The new format of your date string. Default: d/m/Y.
Conclusion
I hope this article and the function can help your work. You can tell me if the function works in your code or not by leaving a comment.