【问题标题】:How to fix MessageFormatter returning incorrect date formatted?如何修复 MessageFormatter 返回格式不正确的日期?
【发布时间】:2019-12-30 07:31:34
【问题描述】:

我有这个简单的代码,以前可以正常工作:

<?php
$dateFormatted = \MessageFormatter::formatMessage(
    'en_US', "{0, date, d MMMM YYYY}", [new \DateTime()]
);

var_dump($dateFormatted); // 28 December 2019

但从 2019 年 12 月 29 日开始,它显示的是明年的日期:

var_dump($dateFormatted); // 29 December 2020

直到 2050 年,我检查的每一年都会发生这种情况。据我所知,它只发生在去年 12 月的几天,但我不确定。 2018 年不受影响。为什么会发生这种情况,有什么解决办法吗?

php 7.1 版

更新:看起来strftime 有同样的问题

Upd2:strftime 显示正确的年份,%Y 但不是 %G

【问题讨论】:

  • 这是一个非常好的问题。但echo strftime("%d %B %Y"); 没问题你的strftime 例子是什么?
  • 是的,echo strftime("%d %B %Y"); 返回正确的日期,这很奇怪,因为 %G 明年仍会返回。谢谢指点

标签: php date formatting strftime


【解决方案1】:

大写 Y 表示 “一年中的一周” (reference),根据 ISO-8601:1988 周数定义,日历年的最后几天通常属于明年的第一周。你想要小写y:

<?php
$dateFormatted = \MessageFormatter::formatMessage(
    'en_US', "{0, date, d MMMM YYYY} / {0, date, d MMMM yyyy}", [new \DateTime('2019-12-29')]
);
var_dump($dateFormatted);
string(37) " 29 December 2020 /  29 December 2019"

【讨论】:

  • 感谢您的澄清。我以为2018年不受影响,结果错了,查了29号,正好是星期六,所以不是新的一周
【解决方案2】:

不幸的是,MessageFormatter 的文档没有解释date 的格式。但我找到了解决方法。你可以使用较低的y。试试:

$dateFormatted = \MessageFormatter::formatMessage(
    'en_US', "{0, date, d MMMM y}", [new \DateTime()]
);
echo $dateFormatted; // 30 December 2019

对于strftime,您可以使用strftime("%d %B %Y")。 我认为这个问题来自ISO_8601 格式标准

【讨论】:

    猜你喜欢
    • 2018-10-11
    • 1970-01-01
    • 2020-11-15
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多