Function to parse date to parts

邮差的信 提交于 2019-12-08 09:12:10

问题


Is there any nice function in PHP to parse the date into parts given the specified format?

e.g.

some_function('20112000', 'dmY') 
some_function('2000-11-20', 'Y-m-d')
some_function('2000 text 11-20', 'Y text m-d')

array('d'=>20, 'm'=>11, 'Y'=>2000) expected in all of the above cases,
(assuming formats compatible with date() function)

Update:

I use PHP 5.1.9
This is also possible using Zend_Date, but it uses different formats than date() (e.g. ddMMyyyy)


回答1:


With PHP >= 5.3, the DateTime::createFromFormat() allows one to parse a date according to a specified format.

After that, you get a DateTime object, and up to your to work with it in order to get the array you want.




回答2:


Write your own:

function ($date, $format = array('d', 'm', 'Y')) {
    $ts = strtotime($date);
    $out = array();
    foreach ($format as $v) {
        $out[$v] = date($v, $ts);
    }
    return $out;
}



回答3:


For PHP < 5.3, look at the more strptime. It uses strftime format, but is sort of what you are looking for.



来源:https://stackoverflow.com/questions/6918740/function-to-parse-date-to-parts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!