开发者

PHP : Function to convert the date format [duplicate]

This question already has answers here: 开发者_如何学JAVA Closed 10 years ago.

Possible Duplicate:

Convert one date format into another in PHP

I want to convert the date format from a particular format to some other.

For example,

Convert the date from ( 2011-06-21 or 2011/06/21 or 06/21/2011 ) to 21062011.

Is there any function to do this job.

Thanks in advance.


var_dump(
    date('dmY', strtotime('2011-06-21')),
    date('dmY', strtotime('2011/06/21')),
    date('dmY', strtotime('06/21/2011'))
);


You should use the DateTime class.

$date = new DateTime('2011-06-21');
echo $date->format('dmY');

It can be used procedurally, if you wish.

var_dump(
    date_format(date_create('2011-06-21'), 'dmY'),
    date_format(date_create('2011/06/21'), 'dmY'),
    date_format(date_create('06/21/2011'), 'dmY')
);


Hi you should be able to to use date combined with strtotime like so

$date; //the date that needs to be formatted
<?php date('dmY', strtotime($date)); ?>

So inside the date() function you simply format the date however you want the original date to be

php strtotime

Hope that helps


Unfortunately dates are very locale specific. strtotime() does not observe all of the niceties of the locale (and date_parse is a simple wrapper around strtotime). e.g. today is 21/06/2011 in the UK, and 06/21/2011 in the US.

A more robust solution is to use the DateTime class and its createFromFormat method.

However, IME, unless you are sourcing the input data from a consistent machine generated source, a better solution is to use a tool which facilitates input in a consistent format

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜