PHP获取特定地区的日期格式

9

如何确定当前给定语言环境的短日期格式呢?

例如,如果我的脚本语言环境设置为荷兰语,我希望以某种方式获取该特定语言环境使用的短日期格式:

dd-mm-yyyy

如果语言环境设置为美国英语,则希望获取美国英语环境下的日期格式:

mm/dd/yyyy

以此类推...


这个回答解决了你的问题吗?根据PHP中的区域设置获取日期格式 - But those new buttons though..
1个回答

12

您可以使用Intl PHP扩展根据选择的语言环境格式化日期:

$locale = 'nl_NL';

$dateObj = new DateTime;
$formatter = new IntlDateFormatter($locale, 
                        IntlDateFormatter::SHORT, IntlDateFormatter::SHORT);

echo $formatter->format($dateObj);
如果你只是想获取用于格式化日期的模式,IntlDateFormatter::getPattern 就是你需要的。
手册中的例子:
$fmt = new IntlDateFormatter(
    'en_US',
    IntlDateFormatter::FULL,
    IntlDateFormatter::FULL,
    'America/Los_Angeles',
    IntlDateFormatter::GREGORIAN,
    'MM/dd/yyyy'
);
echo 'pattern of the formatter is : ' . $fmt->getPattern();
echo 'First Formatted output is ' . $fmt->format(0);
$fmt->setPattern('yyyymmdd hh:mm:ss z');
echo 'Now pattern of the formatter is : ' . $fmt->getPattern();
echo 'Second Formatted output is ' . $fmt->format(0);

这将输出:

pattern of the formatter is : MM/dd/yyyy
First Formatted output is 12/31/1969
Now pattern of the formatter is : yyyymmdd hh:mm:ss z
Second Formatted output is 19690031 04:00:00 PST

@user2723025:这是可能的。只需使用 $formatter->getPattern();。请参见 http://www.php.net/manual/en/intldateformatter.getpattern.php。 - Amal Murali
谢谢Amal,这是格式化$dateObj,我正在寻找的是要返回实际格式(我需要扩展特定格式日期的验证,如您在https://dev59.com/s2Ik5IYBdhLWcg3wbtyb#19271434中的其他帖子中所述)在该帖子中,它仅检查日期是否为“Y-m-d”格式,我需要将其自动适应每个不同的语言环境;-) ,因此对于nl_NL,它将检查“d-m-Y”,希望清楚明了。 - user2723025
非常感谢,我将使用IntlDateFormatter扩展validateDate函数。 - user2723025

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接