Get date format according to the locale in PHP

家住魔仙堡 提交于 2019-12-08 16:02:50

问题


There is a very simple problem. I have a locale identifier, en, en_US, cs_CZ or whatever. I just need to get the date-time format for that locale. I know I can easily format any timestamp or date object according to the locale. But I need just the string representation of the date format, let's say a regular expression. Is there any function managing this functionality? I haven't found any so far...

Exapmle:

$locale = "en_US";
$format = the_function_i_need($locale);
echo $format; // prints something like "month/day/year, hour:minute"

回答1:


converted from comment:

you will have to build an array with a list of the possibilities.

http://en.wikipedia.org/wiki/Date_format_by_country should help.

post the function somewhere when done, i'm sure it would come in handy for others




回答2:


I'm trying to do the same thing myself. Instead of building an array of all the countries, how about using regex to determine the format?

setlocale(LC_TIME, "us_US");

// returns 'mdy'
$type1 = getDateFormat();

setlocale(LC_TIME, "fi_FI");

// returns 'dmy'
$type2 = getDateFormat();

setlocale(LC_TIME, "hu_HU");

// returns 'ymd'
$type3 = getDateFormat();

/**
 * @return string
 */
function getDateFormat()
{
    $patterns = array(
        '/11\D21\D(1999|99)/',
        '/21\D11\D(1999|99)/',
        '/(1999|99)\D11\D21/',
    );
    $replacements = array('mdy', 'dmy', 'ymd');

    $date = new \DateTime();
    $date->setDate(1999, 11, 21);

    return preg_replace($patterns, $replacements, strftime('%x', $date->getTimestamp()));
}



回答3:


function getDateFormat($locale)
{
    $formatter = new IntlDateFormatter($locale, IntlDateFormatter::SHORT, IntlDateFormatter::NONE);
    if ($formatter === null)
        throw new InvalidConfigException(intl_get_error_message());

    return $formatter->getPattern();
}

Make shure you install intl.




回答4:


Use strftime() in conjunction with setlocale(). Seems like it's what you're looking for.



来源:https://stackoverflow.com/questions/8827514/get-date-format-according-to-the-locale-in-php

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