开发者

How to parse any date format

I'm trying to make something clever in order to parse date in any international format.

On my frontend I use jquery ui as a date picker and each languages has its specific date format.

Fr: d/m/Y En: m/d/Y ...

开发者_开发问答

OK but now on the php part I have to store those date using the same format (Mysql Y-m-d). I would like to avoid using switch case and stuff like that so I started to look for another alternative.

The best thing I've found is

http://www.php.net/manual/en/datetime.createfromformat.php That function will enable me to parse the dates if I know the format.

For example

$format = 'Y-m-d';
$date = DateTime::createFromFormat($format, '2009-02-15');

Ok so that's a good start but now I'd like to find the standard date format for the current locale.

So I found this :

http://www.php.net/manual/en/intldateformatter.getpattern.php

But I dont really know how to get it to work because I get inconstitent results:

php > $i = new IntlDateFormatter("fr_FR.utf8",IntlDateFormatter::SHORT,IntlDateFormatter::NONE);
php > echo $i->getPattern();
dd/MM/yy
/* correct ! */

but

php > $i = new IntlDateFormatter("en_US.utf8",IntlDateFormatter::SHORT,IntlDateFormatter::NONE);
php > echo $i->getPattern();                                                    
M/d/yy /* wtf */

Am I missing something ?

Thanks


There is no "universal date format symbol standard". The symbol "y" could be a 2-digit year, a 4-digit year, or even a 3-letter abbreviated month (highly unlikely), depending on the source.

The formatting symbols for IntlDateFormatter are documented here. As you can see from the documentation, for this implementation, "d" is the date without leading zeros, while "dd" contains the leading zeros. Both "M" and "MM" represent the month with leading zeros. The "yy" is the 2-digit year.

There is enough difference between this and jQuery UI's date format symbols that you'll need a data map to map the IntlDateFormatter format symbols to jQuery UI datepicker format symbols, and vice versa.

Something like this should be sufficient (untested):

// PHP => jQuery
$formatMap = array(
    'dd' => 'dd',
    'd'  => 'd',
    'MM' => 'mm',
    'M'  => 'mm',
    'yy' => 'y'
    // and so on...
);

Once you have your map set up, you can create your IntlDateFormatter based on locale, convert that format's symbols into jQuery UI date format symbols, and then send the format to the front-end.

When the user posts back the chosen date, you can do the same in reverse to get back to IntlDateFormatter symbols. At that point, you can use a combination of IntlDateFormatter::setPattern() to set the format to MySQL-style, and datefmt_format() (or equivalent) to actually format the posted date.

Hope this helps.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜