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...
You can use an additional parameter as follows:
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.The
DateTime
class is pretty good at parsing different formats withoutcreateFromFormat()
. 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 theDateTime
class handles this just fine: