【问题标题】:getting always german month-names in PHP在 PHP 中总是获得德语月份名称
【发布时间】:2020-10-18 13:31:06
【问题描述】:

我的 PHP 代码

$now = new \DateTime();
echo $now->format('d. M.')

我得到了什么

12. Dec.(英文)

想要我想要

12. Dez.(德语)

我目前的解决方案

$formatter = new \IntlDateFormatter(
                    "de-DE",
                    \IntlDateFormatter::FULL,
                    \IntlDateFormatter::NONE,
                    "Europe/Berlin",
                    \IntlDateFormatter::GREGORIAN,
                    "dd. MMM"
                    );

echo $formatter->format($now);

问题

总是创建$formatter 有点重。 在使用$now->format('d. M.') 时调用“月份”时是否可以更改php.ini(或类似的)中的某些内容以始终获取德语单词?

我已经在php.ini 中尝试过这个(但没有帮助): intl.default_locale = de

【问题讨论】:

  • 你的方法很好。
  • 呃...您不需要在每次操作日期时都创建格式化程序。对于整个应用程序来说,一个格式化程序实例就足够了。
  • 没错,但对于其他所有“格式”,我都需要一个额外的格式。我的问题是,如果有一种通用的方法可以使 PHP 更加国际化,而不是每次都说,我希望月份/工作日不是英语

标签: php date datetime locale intl


【解决方案1】:

重复:change month name to french

来自http://php.net/manual/en/function.date.php

要格式化其他语言的日期,您应该使用 setlocale() 和 strftime() 函数而不是 date()。

【讨论】:

  • 谢谢,但您的回答只是为我已经存在的“解决方法”(使用 DateTime)提供了另一个“解决方法”(带有时间戳)。我的问题是想知道这是否不能以通用的方式解决。
  • 那没有解决方法,这就是你如何正确地做到这一点。
  • 这取决于您如何称呼它。无论如何:你的回答不适合我的问题。
【解决方案2】:

我打算使用它,您可以在其中创建一个自己的类,它在构造函数中完成所有工作,并且只提供一个简单易用的功能(但仍然可以灵活地更改模式)

class Formatter {
    private $dateFormatter;

    public function __construct() {
        $formatter = new \IntlDateFormatter(
            "de-DE",
            \IntlDateFormatter::MEDIUM,
            \IntlDateFormatter::MEDIUM,
            "Europe/Berlin");
        $this->dateFormatter = $formatter;
    }

    public function printDate(\DateTime $dateTime, string $pattern = null) {
        if ($pattern) {
            $this->dateFormatter->setPattern($pattern);
        }

        return $this->dateFormatter->format($dateTime);
    }
}

用法

$fmt = new Formatter();
echo $fmt->printDate($now, "d. MMM");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    • 2011-03-02
    • 1970-01-01
    相关资源
    最近更新 更多