如何使用单一的php函数以独特的格式更改日期格式

如何使用单一的php函数以独特的格式更改日期格式

本文介绍了如何使用单一的php函数以独特的格式更改日期格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解如何使用php函数将不同的日期格式更改为单一格式。以各种方式尝试后,我无法解决这个难题。顺利地在我的自定义函数.php中使用了下面的代码:

  

DateTime 格式不包含 createFromFormat()。如果您支持的格式(那么 DateTime 类可以处理这个问题:

 $ date = new DateTime($ x); 
return $ date-> format('Ym-d');
}


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');
}

这篇关于如何使用单一的php函数以独特的格式更改日期格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 11:06