I would like to understand how to change different date formats into a single format using a php function. After trying in every way, i wasn't able to solve this puzzle. I always just used the following code in my custom function.php smoothly:
/* Change date format for coupon */
function change_date_format($x) {
$date = DateTime::createFromFormat('j-M-Y', $x);
$x = $date->format('Y-m-d');
return $x;
}
In this way i can convert the format 'j-M-Y' in the format 'Y-m-d'. The problem is that now i need to convert not only the date format 'j-M-Y', but also other formats (for example, i've to convert date format 'j-M-Y' and date format 'Y-m-d\TH:i:sP' in date format 'Y-m-d'. I tried to combine different logic functions but system gives me error.
Thanks to all of you who try to help me...
The DateTime
class is pretty good at parsing different formats without createFromFormat()
. If the formats you have are supported (Supported Date and Time Formats) then just let it create based on the in-built logic. If $x = '2016-06-30T23:59:59+02:00'
then the DateTime
class handles this just fine:
function change_date_format($x) {
$date = new DateTime($x);
return $date->format('Y-m-d');
}
Add an input parameter to your function called: $inputFormat
and use this instead 'j-M-Y'
, so you should specify always the input format. You can specify a default format for input.
/**
* Return with a normal format of any date by given format
* Default format is j-M-Y if no input format given
*
* @param string $dateString
* @param string $inputFormat
* @return string
*/
function change_date_format($dateString, $inputFormat = 'j-M-Y') {
$date = DateTime::createFromFormat($inputFormat, $dateString);
return $date->format('Y-m-d');
}
echo change_date_format('23-05-2016', 'd-m-Y');
echo change_date_format('05/23/2016', 'm/d/Y');
You can use an additional parameter as follows:
/*Change date format for coupon*/
function change_date_format($x, $dateFormat) {
$date = DateTime::createFromFormat($dateFormat, $x);
$x = $date->format('Y-m-d');
return $x;
}