【问题标题】:PHP Datetime fail to convert negative ISO8601 datePHP Datetime 无法转换负 ISO8601 日期
【发布时间】:2015-10-27 22:09:41
【问题描述】:

使用 DateTime 转换负日期让我误会

测试代码

var_dump(\DateTime::createFromFormat(\DateTime::ISO8601, '-0001-11-30T00:00:00+0100'));

结果

boolean false

预期结果

object(DateTime)[5]
  public 'date' => string '-0001-11-30 00:00:00' (length=20)
  public 'timezone_type' => int 1
  public 'timezone' => string '+01:00' (length=6)

(或类似的)

附:负日期字符串是用 $d->format(\DateTime::ISO8601);

创建的

PHP 版本 PHP 5.4.28

【问题讨论】:

  • 为什么不直接使用new DateTime('-0001-11-30T00:00:00+0100');?而 DateTime 类无法知道 +01:00 偏移量是 Europe/Rome 时区...
  • ISO 8601 prescribes, as a minimum, a four-digit year [YYYY] to avoid the year 2000 problem. It therefore represents years from 0000 to 9999, year 0000 being equal to 1 BC and all others AD. However, years prior to 1583 are not automatically allowed by the standard. Instead "values in the range [0000] through [1582] shall only be used by mutual agreement of the partners in information interchange."[
  • 所以我怀疑可能是 format() 而不是 createFromFormat()
  • @Mark 我认为format 并不特别关心 ISO 规范。 DateTime::ISO8601 毕竟只是格式字符串的预设,而不是打开符合 ISO 标准的处理的标志。问题是DateTime::createFromFormat 如何解析负数,或者这根本不可能?
  • @Mark 就我所知,DateTime 根本不承诺任何 ISO 合规性。同样,DateTime::ISO8601 只是字符串Y-m-d\TH:i:sO,仅此而已。 DateTime::format('Y') 会根据自己的意愿返回负值,无论 ISO 对此有何评论。

标签: php datetime iso8601


【解决方案1】:

根据Format的手册

 public string DateTime::format ( string $format )

在哪里

$format

Format accepted by date().

如果你查看date()

$d->format(\DateTime::ISO8601);

应该是

$d->format("c")

因为“c”是根据date()中的格式

ISO 8601 日期(在 PHP 5 中添加)

在我的测试中$d->format(\DateTime::ISO8601); 输出

2015-09-15T00:00:00+0200

同时

$d->format("c");

输出

2015-09-15T00:00:00+02:00

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    • 2012-07-07
    • 1970-01-01
    • 2022-11-23
    • 2016-01-10
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多